<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="keywords" content="课堂行为分析报告,视频行为统计,AI教学评测,教育大数据,学生行为分析,课堂专注度监测,异常行为检测,教学质量评估,郑恩赐技术团队,深度学习教育应用,智能课堂监测,教学数据可视化,YOLOv8教育应用">
    <meta name="description" content="AI课堂教学评测系统的视频分析报告平台，提供实时行为统计、学生专注度分析、课堂异常行为识别和趋势分析，通过丰富的数据可视化助力教师提升教学效果">
    <title>AI课堂教学评测系统 - 视频分析报告</title>
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js" as="script" crossorigin="anonymous">
    <link rel="icon" type="image/png" href="static/icons/AiKeTangJiaoXuePingCeXiTong.png">
    <!-- 添加Markdown支持 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/atom-one-dark.min.css">
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
    <!-- 立即开始加载ECharts，不等待DOM就绪 -->
    <script>
        // 预加载ECharts，优先级比页面资源低
        (function() {
            // 创建预加载的脚本元素
            var preloadScript = document.createElement('script');
            preloadScript.src = 'https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js';
            preloadScript.crossOrigin = 'anonymous';
            preloadScript.async = true; // 异步加载
            
            // 记录加载状态
            window.__echartsLoadStatus = {
                started: true,
                completed: false,
                startTime: Date.now()
            };
            
            // 设置加载完成回调
            preloadScript.onload = function() {
                window.__echartsLoadStatus.completed = true;
                window.__echartsLoadStatus.loadTime = Date.now() - window.__echartsLoadStatus.startTime;
                // console.log('ECharts预加载完成，耗时: ' + window.__echartsLoadStatus.loadTime + 'ms');
                
                // 通知页面ECharts已加载
                if (document.readyState === 'complete' || document.readyState === 'interactive') {
                    // 如果DOM已经准备好，直接触发事件
                    setTimeout(function() {
                        document.dispatchEvent(new Event('echartsLoaded'));
                    }, 0);
                } else {
                    // 否则等待DOM就绪
                    document.addEventListener('DOMContentLoaded', function() {
                        setTimeout(function() {
                            document.dispatchEvent(new Event('echartsLoaded'));
                        }, 0);
                    });
                }
            };
            
            // 添加到文档中
            document.head.appendChild(preloadScript);
        })();
    </script>
    <script>
        const FRONT_END_DOMAIN = "{{ front_end_domain_name }}";
        const BACKEND_DOMAIN = "{{ backend_domain_name }}";
        let currentImageIndex = 0;
        let currentImagePaths = [];
        let imageCache = {};
        let detectionResultCache = {};
        let loadingQueue = [];
        let isLoading = false;
        let preloadBatchSize = 3;
        let totalLoaded = 0;
        let forceFullPreload = true; // 修改为默认开启全量预加载
        let preloadCompleted = false;
        let maxConcurrentLoads = 8; // 最大并行加载数设置为8
        let activeLoads = 0;
        let objectURLs = {};
        let preloadProgress = 0;
        let imageProcessResults = {}; // 用于存储图片处理结果
        let isAutoPlaying = true; // 默认自动播放
        let autoPlayInterval = null; // 自动播放的计时器
        let autoPlaySpeed = 2000; // 自动播放速度，默认
        
        // 添加全局变量，用于防止柱状图重复更新
        window._abnormalChartUpdated = false;
        
        // 在页面变量部分添加全局折线图实例变量和当前时间点变量
        let trendChartInstance = null;
        let currentTimePoint = null;
        
        function loadImagePaths() {
            const videoID = localStorage.getItem('video_id');
            const userToken = localStorage.getItem('token');
            
            if (!videoID || !userToken) {
                showLoadingNotification('缺少必要参数', 3000);
                return;
            }
            
            // 显示加载状态
            showLoadingNotification('正在获取视频帧列表...', 2000);
            
            getVideoImagePathsApi(BACKEND_DOMAIN, userToken, videoID)
                .then(response => {
                    if (response && Array.isArray(response)) {
                        currentImagePaths = response.map(path => {
                            let normalizedPath = path.replace(/\\/g, '/');
                            if (!normalizedPath.startsWith('static/')) {
                                normalizedPath = `static/${normalizedPath}`;
                            }
                            if (!normalizedPath.startsWith('static/video_images/')) {
                                normalizedPath = `static/video_images/${normalizedPath.replace('static/', '')}`;
                            }
                            return normalizedPath;
                        });
                        
                        // 按照整数文件名排序
                        currentImagePaths.sort((a, b) => {
                            // 从路径中提取文件名（数字部分）
                            let numA, numB;
                            const matchA = a.match(/\/(\d+)\.jpg$/);
                            const matchB = b.match(/\/(\d+)\.jpg$/);
                            
                            if (matchA && matchA[1]) {
                                numA = parseInt(matchA[1]);
                            } else {
                                // 尝试其他可能的文件名模式
                                const altMatchA = a.match(/frame_(\d+)/);
                                numA = altMatchA && altMatchA[1] ? parseInt(altMatchA[1]) : 0;
                            }
                            
                            if (matchB && matchB[1]) {
                                numB = parseInt(matchB[1]);
                            } else {
                                // 尝试其他可能的文件名模式
                                const altMatchB = b.match(/frame_(\d+)/);
                                numB = altMatchB && altMatchB[1] ? parseInt(altMatchB[1]) : 0;
                            }
                            
                            return numA - numB;
                        });
                        
                        // console.log('处理后的图片路径:', currentImagePaths);
                        
                        // 显示找到的帧数
                        showLoadingNotification(`找到 ${currentImagePaths.length} 个视频帧，开始全量加载`, 2000);
                        
                        // 启用导航按钮
                        document.getElementById('prev-frame').disabled = currentImageIndex <= 0;
                        document.getElementById('next-frame').disabled = currentImageIndex >= currentImagePaths.length - 1;
                        
                        // 更新帧计数器
                        updateFrameCounter();
                        
                        // 如果有图片路径，立即显示第一张图片
                        if (currentImagePaths.length > 0) {
                            // 立即加载第一张图片
                            loadImageWithRetry(0, 3);
                            
                            // 确保ECharts已加载，如果尚未加载则尝试加载
                            if (!window.echarts) {
                                // console.log('图片加载开始，确保ECharts已就绪');
                                loadECharts()
                                    .then(() => {
                                        // console.log('ECharts已就绪，等待图片处理结果');
                                        // 定时检查图像处理结果
                                        const checkInterval = setInterval(() => {
                                            if (imageProcessResults[currentImageIndex]) {
                                                clearInterval(checkInterval);
                                                // console.log('检测到图像处理结果，更新图表');
                                                
                                                // 先更新所有图表
                                                setTimeout(() => {
                                                    // 更新所有图表
                                                    updateCharts(imageProcessResults[currentImageIndex]);
                                                    
                                                    // 特别确保右边上方的异常行为柱状图被更新
                                                    setTimeout(() => {
                                                        if (document.getElementById('abnormal-behavior-chart')) {
                                                            // console.log('特别检查: 确保异常行为柱状图在第一帧加载时更新');
                                                            const processResult = imageProcessResults[currentImageIndex];
                                                            const stats = {
                                                                use_phone: processResult.use_phone?.length || 0,
                                                                stand: processResult.stand?.length || 0,
                                                                head_on_desk: processResult.head_on_desk?.length || 0,
                                                                look_up: processResult.look_up?.length || 0
                                                            };
                                                            
                                                            // 直接调用更新函数
                                                            updateAbnormalBehaviorChart(
                                                                stats.use_phone,
                                                                stats.stand,
                                                                stats.head_on_desk,
                                                                stats.look_up
                                                            );
                                                            
                                                            // 标记已更新，避免重复更新
                                                            window._abnormalChartUpdated = true;
                                                        }
                                                        
                                                        // 额外检查并更新frame-analysis-summary中的水平柱状图
                                                        if (document.getElementById('behavior-horizontal-bar')) {
                                                            // console.log('特别检查: 确保水平柱状图在第一帧加载时更新');
                                                            updateAnalysisSummary();
                                                        }
                                                    }, 200);
                                                    
                                                    // 额外多次尝试已被移除，避免重复更新引起的抖动问题
                                                    /*
                                                    setTimeout(() => {
                                                        // console.log('再次尝试更新异常行为柱状图(延迟500ms)');
                                                        if (document.getElementById('abnormal-behavior-chart') && 
                                                            imageProcessResults[currentImageIndex]) {
                                                            const processResult = imageProcessResults[currentImageIndex];
                                                            const stats = {
                                                                use_phone: processResult.use_phone?.length || 0,
                                                                stand: processResult.stand?.length || 0,
                                                                head_on_desk: processResult.head_on_desk?.length || 0,
                                                                look_up: processResult.look_up?.length || 0
                                                            };
                                                            updateAbnormalBehaviorChart(
                                                                stats.use_phone,
                                                                stats.stand,
                                                                stats.head_on_desk,
                                                                stats.look_up
                                                            );
                                                        }
                                                        
                                                        // 额外检查并更新frame-analysis-summary中的水平柱状图
                                                        if (document.getElementById('behavior-horizontal-bar')) {
                                                            // console.log('特别检查: 确保水平柱状图在第一帧加载时更新');
                                                            updateAnalysisSummary();
                                                        }
                                                    }, 500);
                                                    */
                                                }, 300);
                                            }
                                        }, 500);
                                        
                                        // 10秒后停止检查
                                        setTimeout(() => clearInterval(checkInterval), 10000);
                                    });
                            }
                            
                            // 修改：加载完成后自动开始播放视频
                            setTimeout(() => {
                                // 自动启动播放
                                startAutoPlay();
                                // 更新播放按钮显示
                                updatePlayButton();
                            }, 1500);
                        } else {
                            showLoadingNotification('没有找到图片', 3000);
                            document.querySelector('.loading-image div').textContent = '未找到任何图片';
                        }
                    } else {
                        showLoadingNotification('获取视频帧失败', 3000);
                        document.querySelector('.loading-image div').textContent = '获取视频帧失败';
                    }
                })
                .catch(error => {
                    console.error('加载图片路径时出错:', error);
                    showLoadingNotification('加载图片路径失败', 3000);
                    document.querySelector('.loading-image div').textContent = '加载图片路径失败，请刷新页面重试';
                    // 添加重试按钮
                    const retryButton = document.createElement('button');
                    retryButton.className = 'analysis-btn';
                    retryButton.style.marginTop = '15px';
                    retryButton.textContent = '重试';
                    retryButton.addEventListener('click', loadImagePaths);
                    document.querySelector('.loading-image').appendChild(retryButton);
                });
        }
        
        function loadImageWithRetry(index, retries) {
            if (retries <= 0) {
                showLoadingNotification(`加载图片失败，请刷新页面重试`, 3000);
                const loadingDetails = document.getElementById('loading-details');
                loadingDetails.textContent = `图片加载失败，已超过最大重试次数`;
                const container = document.querySelector('.loading-image');
                if (!container.querySelector('.retry-btn')) {
                    const retryButton = document.createElement('button');
                    retryButton.className = 'analysis-btn retry-btn';
                    retryButton.style.marginTop = '15px';
                    retryButton.textContent = '重试';
                    retryButton.addEventListener('click', () => loadImageWithRetry(index, 3));
                    container.appendChild(retryButton);
                }
                return;
            }
            
            getVideoImageApi(BACKEND_DOMAIN, localStorage.getItem('token'), currentImagePaths[index])
                .then(blob => {
                    if (blob) {
                        // 检查blob是否有效
                        if (!(blob instanceof Blob)) {
                            console.error(`获取的数据不是有效的Blob对象: ${currentImagePaths[index]}`);
                            setTimeout(() => {
                                loadImageWithRetry(index, retries - 1);
                            }, 1000);
                            return;
                        }
                        
                        const img = new Image();
                        
                        // 添加错误处理
                        img.onerror = (e) => {
                            console.error(`图片加载错误: ${e.message || '未知错误'}`);
                            // 释放之前可能创建的URL
                            if (objectURLs[index]) {
                                URL.revokeObjectURL(objectURLs[index]);
                                delete objectURLs[index];
                            }
                            setTimeout(() => {
                                loadImageWithRetry(index, retries - 1);
                            }, 1000);
                        };
                        
                        img.onload = () => {
                            imageCache[index] = img;
                            totalLoaded++;
                            
                            // 更新进度条
                            preloadProgress = Math.floor((totalLoaded / currentImagePaths.length) * 100);
                            updatePreloadProgress();
                            
                            // 如果是当前显示的帧，立即显示
                            if (index === currentImageIndex) {
                                displayCurrentImage();
                                // 同时加载检测结果
                                loadDetectionResults();
                            }
                            
                            // 同步处理图片获取分析结果
                            processLoadedImage(index, blob);
                            
                            // 如果是第一帧加载完成，启动预加载
                            if (index === 0) {
                                preloadImages();
                            }
                        };
                        
                        // 先释放可能存在的旧URL
                        if (objectURLs[index]) {
                            URL.revokeObjectURL(objectURLs[index]);
                        }
                        
                        // 创建新的URL
                        const objectURL = URL.createObjectURL(blob);
                        objectURLs[index] = objectURL;
                        img.src = objectURL;
                    } else {
                        console.error(`获取图片返回空Blob: ${currentImagePaths[index]} (尝试 ${4-retries}/3)`);
                        setTimeout(() => {
                            loadImageWithRetry(index, retries - 1);
                        }, 1000);
                    }
                })
                .catch(error => {
                    console.error(`获取图片失败: ${currentImagePaths[index]} (尝试 ${4-retries}/3)`, error);
                    showLoadingNotification(`获取图片失败: ${currentImagePaths[index]}`, 2000);
                    setTimeout(() => {
                        loadImageWithRetry(index, retries - 1);
                    }, 1000);
                });
        }
        
        function preloadImages() {
            if (currentImagePaths.length === 0) return;
            
            // 清空队列，准备新一轮加载
            loadingQueue = [];
            
            // 始终加载所有未缓存的帧
            for (let i = 0; i < currentImagePaths.length; i++) {
                if (!imageCache[i] && !loadingQueue.includes(i)) {
                    loadingQueue.push(i);
                }
            }
            
            // 开始多线程处理加载队列
            processLoadingQueue();
        }
        
        function cleanupObjectURLs() {
            Object.keys(objectURLs).forEach(key => {
                try {
                    if (objectURLs[key]) {
                        URL.revokeObjectURL(objectURLs[key]);
                        // console.log(`已释放Blob URL: ${key}`);
                    }
                } catch (err) {
                    console.error(`释放Blob URL时出错: ${key}`, err);
                }
            });
            objectURLs = {};
        }

        // 添加页面可见性变化事件监听，防止页面切换后Blob URL失效
        document.addEventListener('visibilitychange', function() {
            if (document.visibilityState === 'visible') {
                // 页面恢复可见时，检查当前图像是否需要重新加载
                if (currentImageIndex >= 0 && !objectURLs[currentImageIndex]) {
                    // 当前帧的Blob URL已失效，需要重新加载
                    loadImageWithRetry(currentImageIndex, 3);
                }
            }
        });

        window.addEventListener('beforeunload', cleanupObjectURLs);
        
        function processLoadingQueue() {
            if (isLoading || loadingQueue.length === 0) return;
            
            isLoading = true;
            // 每批最多处理8个图片
            const batch = loadingQueue.splice(0, maxConcurrentLoads);
            
            Promise.all(batch.map(index => {
                return new Promise((resolve) => {
                    activeLoads++;
                    loadSingleImageWithRetry(index, 2)
                        .then(() => resolve())
                        .catch(() => resolve())
                        .finally(() => {
                            activeLoads--;
                        });
                });
            })).then(() => {
                isLoading = false;
                if (loadingQueue.length > 0) {
                    // 如果队列中还有图片，继续处理下一批
                    processLoadingQueue();
                } else if (loadingQueue.length === 0 && totalLoaded === currentImagePaths.length) {
                    preloadCompleted = true;
                    showLoadingNotification('所有视频帧加载完成', 2000);
                    
                    // 如果isAutoPlaying为true且尚未开始播放，自动开始播放
                    if (isAutoPlaying && !autoPlayInterval) {
                        startAutoPlay();
                    }
                }
            });
        }
        
        function loadSingleImageWithRetry(index, retries) {
            return new Promise((resolve, reject) => {
                if (imageCache[index]) {
                    resolve();
                    return;
                }
                
                if (retries < 0) {
                    console.error(`获取图片失败，已超过最大重试次数: ${currentImagePaths[index]}`);
                    reject(new Error('超过最大重试次数'));
                    return;
                }
                
                getVideoImageApi(BACKEND_DOMAIN, localStorage.getItem('token'), currentImagePaths[index])
                    .then(blob => {
                        if (blob) {
                            if (typeof blob === 'string') {
                                showLoadingNotification(`加载图片出错: ${blob}`, 3000);
                                setTimeout(() => {
                                    loadSingleImageWithRetry(index, retries - 1)
                                        .then(resolve)
                                        .catch(reject);
                                }, 1000);
                                return;
                            }
                            
                            if (!(blob instanceof Blob)) {
                                console.error(`获取的数据不是有效的Blob对象: ${currentImagePaths[index]}`);
                                setTimeout(() => {
                                    loadSingleImageWithRetry(index, retries - 1)
                                        .then(resolve)
                                        .catch(reject);
                                }, 1000);
                                return;
                            }
                            
                            const img = new Image();
                            img.onload = () => {
                                imageCache[index] = img;
                                totalLoaded++;
                                preloadProgress = Math.floor((totalLoaded / currentImagePaths.length) * 100);
                                updatePreloadProgress();
                                
                                // 同时处理图片并获取分析结果
                                processLoadedImage(index, blob);
                                
                                // 如果当前是显示的图片，立即加载检测结果
                                if (index === currentImageIndex) {
                                    displayCurrentImage();
                                    // 获取当前帧的检测结果
                                    loadDetectionResults();
                                }
                                
                                resolve();
                            };
                            img.onerror = () => {
                                const errorPath = currentImagePaths[index];
                                console.error(`加载图片失败: ${errorPath} (尝试 ${3-retries}/2)`);
                                
                                // 释放之前可能创建的URL
                                if (objectURLs[index]) {
                                    URL.revokeObjectURL(objectURLs[index]);
                                    delete objectURLs[index];
                                }
                                
                                setTimeout(() => {
                                    loadSingleImageWithRetry(index, retries - 1)
                                        .then(resolve)
                                        .catch(reject);
                                }, 800);
                            };
                            
                            // 先释放可能存在的旧URL
                            if (objectURLs[index]) {
                                URL.revokeObjectURL(objectURLs[index]);
                            }
                            
                            // 创建新的URL
                            const objectURL = URL.createObjectURL(blob);
                            objectURLs[index] = objectURL;
                            img.src = objectURL;
                        } else {
                            console.error(`获取图片返回空Blob: ${currentImagePaths[index]} (尝试 ${3-retries}/2)`);
                            
                            setTimeout(() => {
                                loadSingleImageWithRetry(index, retries - 1)
                                    .then(resolve)
                                    .catch(reject);
                            }, 800);
                        }
                    })
                    .catch(error => {
                        console.error(`获取图片失败: ${currentImagePaths[index]} (尝试 ${3-retries}/2)`, error);
                        
                        setTimeout(() => {
                            loadSingleImageWithRetry(index, retries - 1)
                                .then(resolve)
                                .catch(reject);
                        }, 800);
                    });
            });
        }
        
        function updatePreloadProgress() {
            const progressBar = document.querySelector('.preload-progress');
            if (progressBar) {
                progressBar.style.width = `${preloadProgress}%`;
            }
            
            const loadingDetails = document.getElementById('loading-details');
            if (loadingDetails && !imageCache[currentImageIndex]) {
                loadingDetails.textContent = `正在加载第 ${currentImageIndex + 1} 帧，共 ${currentImagePaths.length} 帧 | 总进度: ${preloadProgress}%`;
            }
        }
        
        function displayCurrentImage() {
            const currentImage = document.getElementById('current-image');
            const loadingImage = document.querySelector('.loading-image');
            const detectionCanvas = document.getElementById('detection-canvas');
            const loadingDetails = document.getElementById('loading-details');
            
            if (imageCache[currentImageIndex]) {
                currentImage.src = imageCache[currentImageIndex].src;
                currentImage.style.display = 'block';
                loadingImage.style.display = 'none';
                
                if (currentImage.complete) {
                    detectionCanvas.width = currentImage.width;
                    detectionCanvas.height = currentImage.height;
                    // console.log(`设置canvas尺寸: 宽=${detectionCanvas.width}, 高=${detectionCanvas.height}`);
                } else {
                    currentImage.onload = function() {
                        detectionCanvas.width = currentImage.width;
                        detectionCanvas.height = currentImage.height;
                        // console.log(`图像加载完成后设置canvas尺寸: 宽=${detectionCanvas.width}, 高=${detectionCanvas.height}`);
                    };
                }
                
                // 更新时间指示器
                updateTimeIndicator();
                
                // 加载并显示当前图片的检测结果
                loadDetectionResults();
                
                // 显示图片处理结果
                displayImageProcessResult(currentImageIndex);
                
                // 获取当前选中的行为按钮
                const activeButton = document.querySelector('.behavior-button.active');
                if (activeButton) {
                    // 应用当前选中的行为过滤器
                    applyBehaviorFilter(activeButton.dataset.behavior);
                }
                
                // 启用导航按钮
                document.getElementById('prev-frame').disabled = currentImageIndex <= 0;
                document.getElementById('next-frame').disabled = currentImageIndex >= currentImagePaths.length - 1;
                
                // 更新侧边面板信息
                updateFrameInfoPanel();
                updateBehaviorSummary();
                updateAnalysisSummary();
                updateAbnormalBehaviors();
            } else {
                currentImage.style.display = 'none';
                loadingImage.style.display = 'flex';
                
                // 更新加载详情
                loadingDetails.textContent = `正在加载第 ${currentImageIndex + 1} 帧，共 ${currentImagePaths.length} 帧`;
                document.getElementById('specific-image-progress').style.width = '0%';
                
                // 移除可能存在的重试按钮
                const oldRetryBtn = loadingImage.querySelector('.retry-btn');
                if (oldRetryBtn) {
                    oldRetryBtn.remove();
                }
                
                // 立即加载当前图片
                if (!imageCache[currentImageIndex]) {
                    // 模拟加载进度
                    let fakeProgress = 0;
                    const progressInterval = setInterval(() => {
                        fakeProgress += 5;
                        if (fakeProgress > 90) clearInterval(progressInterval);
                        document.getElementById('specific-image-progress').style.width = `${fakeProgress}%`;
                    }, 100);
                    
                    // 使用重试机制加载图片
                    loadSingleImageWithRetry(currentImageIndex, 3)
                        .then(() => {
                            clearInterval(progressInterval);
                            document.getElementById('specific-image-progress').style.width = '100%';
                            
                            // 图片加载完成后重新显示
                            setTimeout(() => {
                                displayCurrentImage();
                                preloadProgress = Math.floor((totalLoaded / currentImagePaths.length) * 100);
                                updatePreloadProgress();
                            }, 200); // 短暂延迟让进度条完成动画
                        })
                        .catch(error => {
                            clearInterval(progressInterval);
                            console.error('加载当前图片失败:', error);
                            loadingDetails.textContent = `加载失败，请重试`;
                            
                            // 添加重试按钮
                            const retryButton = document.createElement('button');
                            retryButton.className = 'analysis-btn retry-btn';
                            retryButton.style.marginTop = '15px';
                            retryButton.textContent = '重试';
                            retryButton.addEventListener('click', function() {
                                displayCurrentImage();
                            });
                            loadingImage.appendChild(retryButton);
                        });
                }
            }
        }

        function loadDetectionResults() {
            const userToken = localStorage.getItem('token');
            const videoID = localStorage.getItem('video_id');
            
            // 获取当前帧路径
            const currentFramePath = currentImagePaths[currentImageIndex];
            if (!currentFramePath) return;
            
            // 从路径中提取帧编号
            const regex = /\/(\d+)\.jpg$/;
            const match = currentFramePath.match(regex);
            let frameNum = 1;
            
            if (match && match[1]) {
                frameNum = parseInt(match[1]);
            } else {
                console.error('无法从路径获取帧编号:', currentFramePath);
                return;
            }
            
            // 直接使用图像处理结果
            if (imageProcessResults[currentImageIndex]) {
                displayImageProcessResult(currentImageIndex);
            } else {
                console.warn('当前帧尚无处理结果:', currentImageIndex);
                
                // 如果没有处理结果，可以在这里添加提示
                const infoElement = document.getElementById('detection-info');
                if(infoElement) {
                    infoElement.textContent = '正在处理图像...';
                    infoElement.style.display = 'inline-block';
                }
            }
        }
        
        function drawDetectionResults(result) {
            const canvas = document.getElementById('detection-canvas');
            const ctx = canvas.getContext('2d');
            const currentImage = document.getElementById('current-image');
            
            // 清除之前的绘制
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 如果没有检测结果或图像未加载，则返回
            if (!result || !result.detections || !currentImage.complete) return;
            
            const detections = Array.isArray(result.detections) ? result.detections : [result.detections];
            
            // 设置检测框样式
            ctx.lineWidth = 2; // 增加线条宽度，使框更明显
            ctx.font = '14px Arial';
            
            // 行为标识符到中文的映射
            const behaviorMap = {
                "look_up": "抬头",
                "use_phone": "使用手机",
                "stand": "站立",
                "head_on_desk": "趴桌"
            };
            
            // 绘制每个检测结果
            detections.forEach(detection => {
                if (!detection || !detection.bbox) return;
                
                const [x, y, width, height] = detection.bbox;
                const label = detection.label || '未知';
                const confidence = detection.confidence || 0;
                const color = getBehaviorColor(label);
                
                // 转换为中文显示（如果有映射）
                const displayLabel = behaviorMap[label] || label;
                
                // 绘制边界框
                ctx.strokeStyle = color;
                ctx.beginPath();
                ctx.rect(x, y, width, height);
                ctx.stroke();
                
                // 绘制标签背景
                ctx.fillStyle = color; // 去除透明度
                const labelText = `${displayLabel} ${Math.floor(confidence * 100)}%`;
                const labelWidth = ctx.measureText(labelText).width + 10;
                ctx.fillRect(x, y - 20, labelWidth, 20);
                
                // 绘制标签文本
                ctx.fillStyle = '#ffffff';
                ctx.fillText(labelText, x + 5, y - 5);
            });
            
            // 更新检测信息显示
            updateDetectionInfo(result);
        }
        
        function updateDetectionInfo(result) {
            const infoElement = document.getElementById('detection-info');
            
            if (!result || !result.detections || !Array.isArray(result.detections)) {
                infoElement.style.display = 'none';
                return;
            }
            
            const behaviorMap = {
                "look_up": "抬头",
                "use_phone": "使用手机",
                "stand": "站立",
                "head_on_desk": "趴桌"
            };
            
            const behaviorCounts = {};
            result.detections.forEach(detection => {
                const label = detection.label || '未知';
                const displayLabel = behaviorMap[label] || label;
                behaviorCounts[displayLabel] = (behaviorCounts[displayLabel] || 0) + 1;
            });
            
            let infoText = '';
            Object.entries(behaviorCounts).forEach(([behavior, count]) => {
                infoText += ` ${behavior}(${count})`;
            });
            
            infoElement.textContent = infoText;
            infoElement.style.display = 'inline-block';
        }
        
        function getBehaviorColor(behavior) {
            // 为不同行为分配颜色
            const colorMap = {
                "抬头": "#FF4081", // 粉色
                "使用手机": "#33FF57", // 绿色
                "站立": "#3357FF", // 蓝色
                "趴桌": "#9C27B0", // 紫色
                "总人数": "#00f0ff" // 青色
            };
            
            return colorMap[behavior] || '#ffffff'; // 返回对应颜色或默认白色
        }

        // 添加将帧序号转换为视频时间的函数
        function frameToVideoTime(frameIndex, returnSeconds = false) {
            // 获取当前图像路径并提取数字部分
            let imagePath = currentImagePaths[frameIndex];
            let frameNumber = 1; // 默认值
            
            // 从路径提取文件名中的数字部分
            const regex = /\/(\d+)\.jpg$/;
            const match = imagePath.match(regex);
            if (match && match[1]) {
                frameNumber = parseInt(match[1]);
            }
            
            // 当前帧在视频中的秒数 = 帧序号 * 帧提取间隔
            const totalSeconds = frameNumber * window.seconds;
            
            // 如果请求返回秒数，则直接返回
            if (returnSeconds) {
                return totalSeconds;
            }
            
            // 转换为分:秒格式
            const minutes = Math.floor(totalSeconds / 60);
            const seconds = Math.floor(totalSeconds % 60);
            
            // 格式化为 分:秒，秒数不足两位时前面补零
            return `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
        }

        function updateFrameCounter() {
            const counter = document.getElementById('frame-counter');
            if (counter) {
                // 获取视频时间位置
                const videoTime = frameToVideoTime(currentImageIndex);
                counter.textContent = `${currentImageIndex + 1}/${currentImagePaths.length} (${videoTime})`;
            }
            
            // 更新跳转输入框的最大值
            const jumpInput = document.getElementById('frame-jump-input');
            if (jumpInput) {
                jumpInput.max = currentImagePaths.length;
                jumpInput.placeholder = `输入帧号 (1-${currentImagePaths.length})`;
            }
        }

        // 添加一个专门更新时间指示器的函数
        function updateTimeIndicator() {
            const timeIndicator = document.querySelector('.time-indicator');
            if (timeIndicator) {
                const videoTime = frameToVideoTime(currentImageIndex);
                timeIndicator.textContent = `视频位置: ${videoTime}`;
            }
        }

        function navigateFrames(direction) {
            const newIndex = currentImageIndex + direction;
            if (newIndex >= 0 && newIndex < currentImagePaths.length) {
                currentImageIndex = newIndex;
                displayCurrentImage();
                updateFrameCounter();
                preloadImages();
                
                // 更新所有UI组件 - 这会调用所有需要的图表更新
                updateAllUIComponents();
                
                // 移除多余的图表更新代码，避免图表抖动
                /*
                // 强制刷新所有图表
                setTimeout(() => {
                    if (window.echarts && imageProcessResults[currentImageIndex]) {
                        const processResult = imageProcessResults[currentImageIndex];
                        // console.log('帧导航后强制刷新图表');
                        
                        // 确保右边上方的柱状图更新
                        const stats = {
                            use_phone: processResult.use_phone?.length || 0,
                            stand: processResult.stand?.length || 0,
                            head_on_desk: processResult.head_on_desk?.length || 0,
                            look_up: processResult.look_up?.length || 0
                        };
                        
                        // 检查是否已经更新过异常行为柱状图，避免重复更新引起的抖动
                        if (!window._abnormalChartUpdated && document.getElementById('abnormal-behavior-chart')) {
                            // console.log('强制更新异常行为柱状图');
                            updateAbnormalBehaviorChart(
                                stats.use_phone,
                                stats.stand,
                                stats.head_on_desk,
                                stats.look_up
                            );
                            window._abnormalChartUpdated = true;
                        }
                        
                        // 更新其他图表
                        if (document.getElementById('current-frame-pie-chart')) {
                            updatePieChart({...stats, total: Object.values(stats).reduce((a, b) => a + b, 0)});
                        }
                        
                        if (document.getElementById('current-frame-bar-chart')) {
                            updateBarChart({...stats, total: Object.values(stats).reduce((a, b) => a + b, 0)});
                        }
                        
                        // 重置更新标志，为下一次帧切换做准备
                        setTimeout(() => {
                            window._abnormalChartUpdated = false;
                        }, 500);
                    }
                }, 100);
                */
            } else if (newIndex >= currentImagePaths.length && isAutoPlaying) {
                // 如果启用了自动播放并且到达最后一帧，则循环回第一帧
                currentImageIndex = 0;
                displayCurrentImage();
                updateFrameCounter();
                preloadImages();
                
                // 更新所有UI组件
                updateAllUIComponents();
                
                // 移除多余的图表更新代码，避免图表抖动
                /*
                // 强制刷新所有图表
                setTimeout(() => {
                    if (window.echarts && imageProcessResults[currentImageIndex]) {
                        const processResult = imageProcessResults[currentImageIndex];
                        // console.log('循环播放强制刷新图表');
                        
                        // 确保右边上方的柱状图更新
                        const stats = {
                            use_phone: processResult.use_phone?.length || 0,
                            stand: processResult.stand?.length || 0,
                            head_on_desk: processResult.head_on_desk?.length || 0,
                            look_up: processResult.look_up?.length || 0
                        };
                        
                        // 检查是否已经更新过异常行为柱状图，避免重复更新引起的抖动
                        if (!window._abnormalChartUpdated && document.getElementById('abnormal-behavior-chart')) {
                            // console.log('强制更新异常行为柱状图');
                            updateAbnormalBehaviorChart(
                                stats.use_phone,
                                stats.stand,
                                stats.head_on_desk,
                                stats.look_up
                            );
                            window._abnormalChartUpdated = true;
                        }
                        
                        // 更新其他图表
                        if (document.getElementById('current-frame-pie-chart')) {
                            updatePieChart({...stats, total: Object.values(stats).reduce((a, b) => a + b, 0)});
                        }
                        
                        if (document.getElementById('current-frame-bar-chart')) {
                            updateBarChart({...stats, total: Object.values(stats).reduce((a, b) => a + b, 0)});
                        }
                        
                        // 重置更新标志，为下一次帧切换做准备
                        setTimeout(() => {
                            window._abnormalChartUpdated = false;
                        }, 500);
                    }
                }, 100);
                */
            }
        }
        
        function jumpToFrame(frameNumber) {
            // 确保帧号在有效范围内（1到最大帧数）
            if (frameNumber >= 1 && frameNumber <= currentImagePaths.length) {
                // 将用户输入的帧号转换为数组索引（减1）
                const newIndex = frameNumber - 1;
                
                // 如果是不同的帧，则进行跳转
                if (newIndex !== currentImageIndex) {
                    currentImageIndex = newIndex;
                    displayCurrentImage();
                    updateFrameCounter();
                    preloadImages();
                    
                    // 更新高亮显示的时间点
                    const timePointInSeconds = frameToVideoTime(currentImageIndex, true);
                    if (trendChartInstance && timePointInSeconds) {
                        highlightTimePointInChart(timePointInSeconds);
                    }
                }
            } else {
                // 显示错误消息
                showLoadingNotification(`请输入有效的帧号 (1-${currentImagePaths.length})`, 2000);
            }
        }
        
        // 添加页面加载状态管理
        document.addEventListener('DOMContentLoaded', function() {
            // console.log('DOM加载完成，等待资源...');
            
            // 修改：移除自动播放启动，只有用户点击按钮才会启动自动播放
            isAutoPlaying = false; // 默认设置为不自动播放
            updatePlayButton(); // 更新按钮状态
        });
        
        window.addEventListener('load', function() {
            // console.log('所有资源加载完成');
            
            // 页面加载完成后，添加额外的图表初始化检查
            setTimeout(() => {
                // console.log('页面加载后，额外检查所有图表是否已初始化');
                
                if (window.echarts && imageProcessResults[currentImageIndex]) {
                    const processResult = imageProcessResults[currentImageIndex];
                    
                    // 特别检查并更新异常行为柱状图
                    if (document.getElementById('abnormal-behavior-chart')) {
                        // console.log('页面加载后特别确保更新异常行为柱状图');
                        const stats = {
                            use_phone: processResult.use_phone?.length || 0,
                            stand: processResult.stand?.length || 0,
                            head_on_desk: processResult.head_on_desk?.length || 0,
                            look_up: processResult.look_up?.length || 0
                        };
                        
                        // 直接调用更新函数
                        updateAbnormalBehaviorChart(
                            stats.use_phone,
                            stats.stand,
                            stats.head_on_desk,
                            stats.look_up
                        );
                        
                        // 如果需要，强制重置图表
                        setTimeout(() => {
                            const chartDom = document.getElementById('abnormal-behavior-chart');
                            if (chartDom) {
                                let chart = echarts.getInstanceByDom(chartDom);
                                if (chart) {
                                    // 如果图表已存在，先销毁再重新创建
                                    chart.dispose();
                                }
                                chart = echarts.init(chartDom);
                                
                                // 重新应用数据
                                updateAbnormalBehaviorChart(
                                    stats.use_phone,
                                    stats.stand,
                                    stats.head_on_desk,
                                    stats.look_up
                                );
                            }
                        }, 500);
                    }
                    
                    // 检查并更新其他图表
                    updateAllUIComponents();
                }
            }, 1000);
        });
        
        // 处理加载完成的图片，调用processImageApi函数并保存结果
        async function processLoadedImage(index, blob) {
            try {
                const token = localStorage.getItem('token');
                const videoID = localStorage.getItem('video_id');
                
                // 获取视频分析类别
                const classes = await getVideoClassesApi(BACKEND_DOMAIN, token, videoID);
                
                if (!classes || classes.length === 0) {
                    console.warn('未找到行为类别，无法处理图片');
                    return;
                }
                
                // console.log(`开始处理第${index+1}张图片，使用类别:`, classes);
                
                // 同时处理图片并获取分析结果
                const result = await processImageApi(BACKEND_DOMAIN, token, classes, blob);
                
                if (result && result.TF) {
                    // 存储图片处理结果到缓存
                    imageProcessResults[index] = result.data;
                    // console.log(`第${index+1}张图片处理完成:`, result.data);
                    
                    // 如果是当前显示的图片，立即更新显示结果
                    if (index === currentImageIndex) {
                        displayImageProcessResult(index);
                        
                        // 应用当前选定的行为过滤器
                        const activeButton = document.querySelector('.behavior-button.active');
                        if (activeButton) {
                            applyBehaviorFilter(activeButton.dataset.behavior);
                        }
                    }
                } else {
                    console.error(`处理第${index+1}张图片失败:`, result.message);
                }
            } catch (error) {
                console.error(`处理图片时出错(索引${index}):`, error);
            }
        }
        
        // 显示图片处理结果
        function displayImageProcessResult(index) {
            const processResult = imageProcessResults[index];
            if (!processResult) {
                return;
            }

            const currentImage = document.getElementById('current-image');
            if (currentImage && currentImage.complete) {
                if (processResult && typeof processResult === 'object') {
                    Object.entries(processResult).forEach(([behavior, boxes]) => {
                        if (Array.isArray(boxes) && boxes.length > 0) {
                        }
                    });
                }
            }

            const detectionInfo = document.getElementById('detection-info');
            if (!detectionInfo) return;

            const activeButton = document.querySelector('.behavior-button.active');
            const selectedBehavior = activeButton ? activeButton.dataset.behavior : 'all';

            try {
                detectionInfo.style.display = 'none';
                drawDetectionBoxes(processResult, selectedBehavior);
                
                // 更新饼图和柱状图 (不含异常行为柱状图)
                // 避免在这里调用updateCharts，因为它会触发多个图表更新，包括异常行为柱状图
                // 直接调用需要的单个图表更新函数
                if (window.echarts) {
                    const stats = {
                        use_phone: processResult.use_phone?.length || 0,
                        stand: processResult.stand?.length || 0,
                        head_on_desk: processResult.head_on_desk?.length || 0,
                        look_up: processResult.look_up?.length || 0,
                        total: 0
                    };
                    
                    // 计算总数
                    stats.total = Object.values(stats).reduce((sum, count) => sum + count, 0);
                    
                    // 更新异常行为柱状图（添加标志位检查，避免重复更新）
                    if (!window._abnormalChartUpdated && document.getElementById('abnormal-behavior-chart')) {
                        updateAbnormalBehaviorChart(
                            stats.use_phone,
                            stats.stand,
                            stats.head_on_desk,
                            stats.look_up
                        );
                        window._abnormalChartUpdated = true;
                        
                        // 延迟重置标志
                        setTimeout(() => {
                            window._abnormalChartUpdated = false;
                        }, 500);
                    }
                    
                    // 单独更新饼图和普通柱状图
                    // updatePieChart({...stats});
                    // updateBarChart({...stats});
                    
                    // 更新水平柱状图
                    updateAnalysisSummary();
                    
                    // 更新其他图表
                    updateBehaviorPieChart();
                    updateFrameInfoRadarChart();
                    
                    // 获取当前时间点并高亮显示在折线图上
                    const timePointInSeconds = frameToVideoTime(index, true);
                    if (trendChartInstance && timePointInSeconds) {
                        highlightTimePointInChart(timePointInSeconds);
                    }
                }
                
                // 移除额外的延迟图表更新，避免柱状图抖动问题
                /*
                // 确保图表最终会被显示，即使ECharts加载延迟
                setTimeout(() => {
                    if (window.echarts && document.getElementById('current-frame-pie-chart')) {
                        // console.log('延迟检查: 确保图表已更新');
                        updateCharts(processResult);
                        
                        // 单独确保所有图表都已更新
                        if (document.getElementById('behavior-pie-chart')) {
                            // console.log('确保行为饼图已更新');
                            updateBehaviorPieChart();
                        }
                        if (document.getElementById('frame-info-radar-chart')) {
                            // console.log('确保雷达图已更新');
                            updateFrameInfoRadarChart();
                        }
                        if (document.getElementById('abnormal-behavior-chart')) {
                            // console.log('确保异常行为柱状图已更新');
                            const stats = processResult ? {
                                use_phone: processResult.use_phone?.length || 0,
                                stand: processResult.stand?.length || 0,
                                head_on_desk: processResult.head_on_desk?.length || 0,
                                look_up: processResult.look_up?.length || 0
                            } : {};
                            updateAbnormalBehaviorChart(
                                stats.use_phone || 0,
                                stats.stand || 0,
                                stats.head_on_desk || 0,
                                stats.look_up || 0
                            );
                        }
                        
                        // 确保水平柱状图也更新
                        updateAnalysisSummary();
                    } else {
                        // console.log('图表元素或ECharts尚未准备好，再次延迟');
                        // 再次延迟检查
                        setTimeout(() => {
                            if (window.echarts) {
                                // console.log('二次延迟后更新图表');
                                updateCharts(processResult);
                                
                                // 二次延迟后单独确保所有图表都已更新
                                if (document.getElementById('behavior-pie-chart')) {
                                    updateBehaviorPieChart();
                                }
                                if (document.getElementById('frame-info-radar-chart')) {
                                    updateFrameInfoRadarChart();
                                }
                                if (document.getElementById('abnormal-behavior-chart')) {
                                    const stats = processResult ? {
                                        use_phone: processResult.use_phone?.length || 0,
                                        stand: processResult.stand?.length || 0,
                                        head_on_desk: processResult.head_on_desk?.length || 0,
                                        look_up: processResult.look_up?.length || 0
                                    } : {};
                                    updateAbnormalBehaviorChart(
                                        stats.use_phone || 0,
                                        stats.stand || 0,
                                        stats.head_on_desk || 0,
                                        stats.look_up || 0
                                    );
                                }
                                
                                // 二次延迟后确保水平柱状图也更新
                                updateAnalysisSummary();
                            }
                        }, 1000);
                    }
                }, 500);
                */
            } catch (error) {
                console.error('显示图像处理结果时出错:', error);
            }
        }

        // 新增函数：绘制检测框
        function drawDetectionBoxes(processResult, selectedBehavior) {
            const canvas = document.getElementById('detection-canvas');
            const ctx = canvas.getContext('2d');
            const currentImage = document.getElementById('current-image');
            
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            if (!currentImage.complete || !processResult) return;
            
            canvas.width = currentImage.clientWidth;
            canvas.height = currentImage.clientHeight;
            
            // console.log(`Canvas尺寸: 宽=${canvas.width}, 高=${canvas.height}`);
            // console.log(`图像显示尺寸: 宽=${currentImage.clientWidth}, 高=${currentImage.clientHeight}`);
            
            const scaleX = canvas.width / currentImage.naturalWidth;
            const scaleY = canvas.height / currentImage.naturalHeight;
            
            ctx.lineWidth = 2; // 增加线条宽度，使框更明显
            
            function transformCoordinates(box) {
                if (!Array.isArray(box) || box.length !== 4) return null;
                
                const x1 = Math.round(box[0] * scaleX);
                const y1 = Math.round(box[1] * scaleY);
                const x2 = Math.round(box[2] * scaleX);
                const y2 = Math.round(box[3] * scaleY);
                
                return {
                    x: x1,
                    y: y1,
                    width: x2 - x1,
                    height: y2 - y1
                };
            }
            
            const colorMap = {
                'head_on_desk': '#9C27B0', // 紫色
                'use_phone': '#33FF57',    // 绿色
                'stand': '#3357FF',        // 蓝色
                'yolo_model_output': '#FFFF33', // 黄色
                'look_up': '#FF4081'       // 粉色
            };
            
            if (selectedBehavior === 'all') {
                Object.entries(processResult).forEach(([behavior, boxes]) => {
                    if (Array.isArray(boxes)) {
                        boxes.forEach(box => {
                            if (Array.isArray(box) && box.length === 4) {
                                // 设置颜色
                                ctx.strokeStyle = colorMap[behavior] || '#FFFFFF';
                                
                                // 直接绘制边界框
                                const [x1, y1, x2, y2] = box;
                                const boxWidth = x2 - x1;
                                const boxHeight = y2 - y1;
                                ctx.strokeRect(
                                    Math.round(x1 * scaleX), 
                                    Math.round(y1 * scaleY), 
                                    Math.round(boxWidth * scaleX), 
                                    Math.round(boxHeight * scaleY)
                                );
                            }
                        });
                    }
                });
            } else {
                // 只显示选中的行为类别
                const boxes = processResult[selectedBehavior];
                if (Array.isArray(boxes)) {
                    boxes.forEach(box => {
                        if (Array.isArray(box) && box.length === 4) {
                            // 设置颜色
                            ctx.strokeStyle = colorMap[selectedBehavior] || '#FFFFFF';
                            
                            // 直接绘制边界框
                            const [x1, y1, x2, y2] = box;
                            const boxWidth = x2 - x1;
                            const boxHeight = y2 - y1;
                            ctx.strokeRect(
                                Math.round(x1 * scaleX), 
                                Math.round(y1 * scaleY), 
                                Math.round(boxWidth * scaleX), 
                                Math.round(boxHeight * scaleY)
                            );
                        }
                    });
                }
            }
        }
        
        // 添加窗口调整大小事件处理
        let resizeTimeout;
        window.addEventListener('resize', function() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                const activeButton = document.querySelector('.behavior-button.active');
                const selectedBehavior = activeButton ? activeButton.dataset.behavior : 'all';
                
                const currentImage = document.getElementById('current-image');
                if (currentImage && currentImage.complete && detectionResultCache[currentImageIndex]) {
                    drawDetectionBoxes(detectionResultCache[currentImageIndex], selectedBehavior);
                }
            }, 200);
        });
    </script>
    <script src="{{ url_for('static', filename='javascripts/ShowVideoProcessedResult.js') }}" defer></script>
    <script>
        // 将现有的loadECharts函数替换为更高效的版本，添加事件广播和超时检测
        function loadECharts() {
            return new Promise((resolve, reject) => {
                // 如果已经加载，立即返回
                if (window.echarts) {
                    // console.log('ECharts已加载，无需重新加载');
                    return resolve(window.echarts);
                }
                
                // 设置超时检测
                const timeout = setTimeout(() => {
                    console.warn('ECharts加载超时，尝试本地检测');
                    if (window.echarts) {
                        // console.log('超时后检测到ECharts已加载');
                        clearTimeout(timeout);
                        resolve(window.echarts);
                    } else {
                        loadFallbackECharts();
                    }
                }, 5000);
                
                // 主要加载逻辑
                const script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js';
                script.crossOrigin = 'anonymous';
                script.onload = () => {
                    clearTimeout(timeout);
                    // console.log('ECharts CDN加载成功');
                    window.echarts = echarts;
                    // 触发加载完成事件
                    document.dispatchEvent(new Event('echartsLoaded'));
                    resolve(window.echarts);
                };
                script.onerror = () => {
                    clearTimeout(timeout);
                    loadFallbackECharts();
                };
                document.head.appendChild(script);
                
                // 加载备用CDN的函数
                function loadFallbackECharts() {
                    console.warn('使用备用CDN加载ECharts');
                    const fallbackScript = document.createElement('script');
                    fallbackScript.src = 'https://cdn.bootcdn.net/ajax/libs/echarts/5.4.3/echarts.min.js';
                    fallbackScript.crossOrigin = 'anonymous';
                    fallbackScript.onload = () => {
                        // console.log('ECharts备用CDN加载成功');
                        window.echarts = echarts;
                        // 触发加载完成事件
                        document.dispatchEvent(new Event('echartsLoaded'));
                        resolve(window.echarts);
                    };
                    fallbackScript.onerror = () => {
                        console.error('所有ECharts CDN加载失败');
                        showLoadingNotification('图表库加载失败，部分功能可能无法使用', 5000);
                        reject(new Error('ECharts加载失败'));
                    };
                    document.head.appendChild(fallbackScript);
                }
            });
        }

        document.addEventListener('DOMContentLoaded', () => {
            // console.log('DOM加载完毕，开始加载ECharts');
            
            // 在页面加载时预加载ECharts
            loadECharts()
                .then(echarts => {
                    // console.log('ECharts预加载成功');
                    // 主动触发重新绘制当前帧的图表
                    if (imageProcessResults && imageProcessResults[currentImageIndex]) {
                        // console.log('检测到当前帧数据，准备更新图表');
                        setTimeout(() => {
                            updateCharts(imageProcessResults[currentImageIndex]);
                            // console.log('已触发图表更新');
                        }, 300);
                    }
                })
                .catch(error => {
                    console.error('ECharts预加载失败:', error);
                });
            
            // 添加水波纹效果处理
            setupRippleEffects();
        });
        
        // 添加水波纹效果
        function setupRippleEffects() {
            const rippleItems = document.querySelectorAll('.meta-item, .stat-mini-item, .behavior-button');
            
            rippleItems.forEach(item => {
                item.classList.add('ripple-effect');
                
                item.addEventListener('click', function(e) {
                    const rippleElement = this;
                    rippleElement.classList.remove('active');
                    
                    // 触发重排
                    void rippleElement.offsetWidth;
                    
                    // 获取点击位置相对于元素的坐标
                    const rect = rippleElement.getBoundingClientRect();
                    const x = e.clientX - rect.left;
                    const y = e.clientY - rect.top;
                    
                    // 设置渐变起点位置
                    rippleElement.style.setProperty('--ripple-x', `${x}px`);
                    rippleElement.style.setProperty('--ripple-y', `${y}px`);
                    
                    // 添加active类以触发动画
                    rippleElement.classList.add('active');
                });
            });
        }
        
        // 高亮显示变化内容
        function highlightChanges(elementIds) {
            if (!Array.isArray(elementIds)) {
                elementIds = [elementIds];
            }
            
            elementIds.forEach(id => {
                const element = document.getElementById(id);
                if (element) {
                    // 移除现有动画以便重新应用
                    element.classList.remove('highlight-change');
                    
                    // 触发重排
                    void element.offsetWidth;
                    
                    // 添加高亮动画类
                    element.classList.add('highlight-change');
                }
            });
        }
        
        // 在帧切换时更新所有UI元素
        function updateAllUIComponents() {
            // 更新各个UI组件
            updateFrameInfoPanel();
            updateBehaviorSummary();
            updateAnalysisSummary();
            // 注意：updateAbnormalBehaviors()内部会调用updateAbnormalBehaviorChart()
            // 所以不需要在这里重复调用两次柱状图更新函数
            updateAbnormalBehaviors();
            
            // 直接调用其他图表更新函数
            if (window.echarts && imageProcessResults[currentImageIndex]) {
                const processResult = imageProcessResults[currentImageIndex];
                
                // 不再重复调用updateAbnormalBehaviorChart，避免柱状图抖动
                // 上面的updateAbnormalBehaviors函数已经会更新异常行为柱状图
                
                // 更新其他图表
                updateCharts(processResult);
                updateBehaviorPieChart();
                updateFrameInfoRadarChart();
            }
            
            // 高亮变化的元素
            highlightChanges([
                'current-frame-number',
                'current-frame-time',
                'detection-count',
                'frame-analysis-summary'
            ]);
            
            // 在DOM更新后，重新设置水波纹效果
            setTimeout(() => {
                setupRippleEffects();
            }, 100);
        }
    </script>
    <style>
        .content-loading {
            opacity: 0;
            transition: opacity 0.5s ease;
        }
        
        .content-loaded {
            opacity: 1;
        }
        
        .no-fouc {
            visibility: visible;
            opacity: 1;
        }
        
        .skeleton-loading {
            background: linear-gradient(90deg, rgba(30, 30, 60, 0.3) 25%, rgba(40, 40, 80, 0.5) 50%, rgba(30, 30, 60, 0.3) 75%);
            background-size: 200% 100%;
            animation: skeleton-loading 1.5s infinite;
        }
        
        @keyframes skeleton-loading {
            0% { background-position: 200% 0; }
            100% { background-position: -200% 0; }
        }
        
        .chart {
            width: 100%;
            height: 500px;
            min-height: 300px;
        }
        
        /* 添加图表容器布局优化样式 */
        .chart-flex-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-top: 15px;
            justify-content: space-between;
        }
        
        .chart-box {
            background-color: rgba(15, 15, 35, 0.7);
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 0 10px rgba(0, 240, 255, 0.1);
            border: 1px solid rgba(0, 240, 255, 0.2);
            flex: 1;
            min-width: 45%;
            transition: box-shadow 0.3s ease;
        }
        
        .chart-box:hover {
            box-shadow: 0 0 15px rgba(0, 240, 255, 0.3);
        }
        
        .chart-box h3 {
            color: #00f0ff;
            margin-top: 0;
            text-align: center;
            font-size: 18px;
            margin-bottom: 15px;
            font-weight: normal;
            text-shadow: 0 0 5px rgba(0, 240, 255, 0.5);
        }
        
        @media (max-width: 992px) {
            .chart-flex-container {
                flex-direction: column;
            }
            
            .chart-box {
                width: 100%;
                min-width: 100%;
                margin-bottom: 20px;
            }
            
            .chart {
                height: 350px;
                min-height: 250px;
            }
        }
        
        .video-preview-content {
            min-height: 300px;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #121223;
            color: #e0e0ff;
            margin: 0;
            padding: 20px;
            line-height: 1.6;
            display: flex;
            flex-direction: column;
            min-height: 100vh;
            overflow-x: hidden;
        }

        .video-preview-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 30px;
            position: relative;
            background-color: rgba(20, 20, 40, 0.7);
            border-radius: 8px;
            box-shadow: 0 2px 15px rgba(88, 101, 242, 0.3);
            padding: 15px;
            border: 1px solid rgba(65, 128, 255, 0.3);
        }

        .report-header {
            text-align: center;
            margin-bottom: 20px;
        }

        .chart-container {
            background-color: rgba(20, 20, 40, 0.7);
            border-radius: 8px;
            box-shadow: 0 2px 15px rgba(88, 101, 242, 0.3);
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid rgba(65, 128, 255, 0.3);
        }

        .error-message {
            color: #ff5e5e;
            text-align: center;
            font-size: 18px;
            padding: 30px;
        }

        .loading {
            text-align: center;
            padding: 20px;
            font-size: 16px;
            color: #00f0ff;
        }
        
        .chart-tip {
            text-align: center;
            color: #00d0ff;
            font-size: 14px;
            margin: 5px 0 15px 0;
            font-style: italic;
        }

        .back-button {
            position: absolute;
            top: 20px;
            left: 20px;
            padding: 8px 16px;
            background-color: rgba(84, 112, 198, 0.2);
            color: #00f0ff;
            border: 1px solid #5470c6;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            z-index: 100;
        }

        .back-button:hover {
            background-color: rgba(84, 112, 198, 0.5);
            box-shadow: 0 0 10px #5470c6;
        }

        .stats-panel {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
            padding: 20px;
            background: rgba(20, 20, 40, 0.7);
            border-radius: 10px;
            box-shadow: 0 5px 25px rgba(88, 101, 242, 0.4);
            border: 1px solid rgba(65, 128, 255, 0.3);
            position: relative;
            overflow: auto;
            max-width: 100%;
        }

        .stats-panel::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: 
                radial-gradient(circle at 10% 20%, rgba(0, 240, 255, 0.15), transparent 20%),
                radial-gradient(circle at 80% 60%, rgba(88, 101, 242, 0.1), transparent 25%);
            pointer-events: none;
        }

        @media (max-width: 768px) {
            .stats-panel {
                grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
                padding: 15px 10px;
                gap: 15px;
                overflow-x: auto;
            }
            
            .stat-item {
                padding: 12px;
                min-width: 140px;
            }
            
            .ai-analysis-container {
                flex-direction: column;
            }
            
            .ai-analysis-left, 
            .ai-analysis-right {
                width: 100%;
                padding: 0;
                margin-bottom: 15px;
            }
        }

        .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 18px;
            background: linear-gradient(135deg, rgba(40, 44, 80, 0.7), rgba(25, 25, 50, 0.8));
            border-radius: 8px;
            border-left: 3px solid #00f0ff;
            box-shadow: 0 0 15px rgba(0, 240, 255, 0.3);
            position: relative;
            overflow: hidden;
            transition: all 0.3s ease;
            animation: glowPulse 2s infinite alternate;
            text-align: center;
            height: 100%;
            max-width: 180px; /* 添加最大宽度限制 */
            margin: 0 auto; /* 确保居中显示 */
            word-break: break-word; /* 防止长文本溢出 */
        }

        @keyframes glowPulse {
            0% {
                box-shadow: 0 0 10px rgba(0, 240, 255, 0.3);
            }
            100% {
                box-shadow: 0 0 20px rgba(0, 240, 255, 0.6);
            }
        }

        .stat-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 0 25px rgba(0, 240, 255, 0.7);
        }

        .stat-item::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(90deg, transparent, #00f0ff, transparent);
            z-index: 1;
        }

        .stat-item::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(0, 240, 255, 0.5), transparent);
            z-index: 1;
        }

        .stat-item strong {
            color: #99e6ff;
            font-size: 0.9rem;
            font-weight: bold;
            margin-bottom: 10px;
            position: relative;
            display: block;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .stat-item .stat-value {
            font-size: 2rem;
            font-weight: bold;
            color: #00f0ff;
            text-shadow: 0 0 10px rgba(0, 240, 255, 0.8);
            animation: textPulse 2s infinite alternate;
            margin: 8px 0;
        }

        @keyframes textPulse {
            0% {
                text-shadow: 0 0 10px rgba(0, 240, 255, 0.5);
            }
            100% {
                text-shadow: 0 0 20px rgba(0, 240, 255, 0.9), 0 0 30px rgba(0, 240, 255, 0.4);
            }
        }

        .stat-item .stat-percentage {
            font-size: 0.9rem;
            color: #7adbff;
            letter-spacing: 0.5px;
        }

        .color-block {
            display: block;
            width: 40px;
            height: 4px;
            margin: 0 auto 12px;
            box-shadow: 0 0 8px rgba(255, 255, 255, 0.7);
            border-radius: 2px;
            position: relative;
        }
        
        .color-block::before, 
        .color-block::after {
            content: '';
            position: absolute;
            height: 100%;
            width: 15%;
            top: 0;
            background-color: rgba(255, 255, 255, 0.8);
            box-shadow: 0 0 5px rgba(255, 255, 255, 0.8);
        }
        
        .color-block::before {
            left: -10%;
        }
        
        .color-block::after {
            right: -10%;
        }

        .ai-analysis-container {
            background-color: rgba(20, 20, 40, 0.7);
            border-radius: 8px;
            box-shadow: 0 2px 15px rgba(88, 101, 242, 0.3);
            padding: 15px;
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            border: 1px solid rgba(65, 128, 255, 0.3);
            overflow: hidden;
            max-width: 100%;
        }

        .ai-analysis-left {
            width: 50%;
            overflow: hidden;
        }

        .ai-analysis-right {
            width: 48%;
            padding-left: 2%;
            overflow: hidden;
        }

        .ai-analysis-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            color: #00f0ff;
        }

        .ai-analysis-content {
            line-height: 1.6;
            padding: 15px;
            background-color: rgba(40, 44, 80, 0.5);
            border-radius: 4px;
            white-space: pre-line;
            overflow: auto;
            max-height: 500px;
            word-wrap: break-word;
            /* 添加自定义滚动条样式 */
            scrollbar-width: thin;
            scrollbar-color: rgba(0, 240, 255, 0.6) rgba(20, 20, 40, 0.2);
        }

        /* 为Webkit浏览器(Chrome, Safari等)添加自定义滚动条样式 */
        .ai-analysis-content::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        .ai-analysis-content::-webkit-scrollbar-track {
            background: rgba(20, 20, 40, 0.2);
            border-radius: 4px;
        }

        .ai-analysis-content::-webkit-scrollbar-thumb {
            background: rgba(0, 240, 255, 0.6);
            border-radius: 4px;
            box-shadow: inset 0 0 6px rgba(0, 240, 255, 0.4);
        }

        .ai-analysis-content::-webkit-scrollbar-thumb:hover {
            background: rgba(0, 240, 255, 0.8);
            box-shadow: inset 0 0 8px rgba(0, 240, 255, 0.6);
        }

        .ai-loading {
            padding: 15px;
            text-align: center;
            color: #00b4ff;
        }

        .pie-chart {
            width: 100%;
            height: 340px;
            overflow: hidden;
        }

        .analysis-btn {
            padding: 8px 16px;
            background-color: rgba(84, 112, 198, 0.2);
            color: #00f0ff;
            border: 1px solid #5470c6;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .analysis-btn:hover {
            background-color: rgba(84, 112, 198, 0.5);
            box-shadow: 0 0 10px #5470c6;
        }

        .analysis-btn:disabled {
            background-color: rgba(160, 160, 160, 0.3);
            cursor: not-allowed;
        }

        .radar-chart {
            width: 100%;
            overflow: hidden;
        }

        .chart-container.radar {
            margin-top: 20px;
        }

        .frame-navigation {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            width: 100%;
            display: flex;
            justify-content: space-between;
            z-index: 10;
            pointer-events: none;
        }

        /* 播放控制相关样式 */
        .playback-controls {
            display: flex;
            align-items: center;
            gap: 15px;
            background-color: rgba(0, 10, 20, 0.8);
            padding: 8px 15px;
            border-radius: 30px;
            border: 1px solid rgba(0, 240, 255, 0.4);
            box-shadow: 
                0 0 10px rgba(0, 240, 255, 0.3),
                inset 0 0 15px rgba(0, 240, 255, 0.1);
            position: relative;
            overflow: hidden;
            backdrop-filter: blur(5px);
            transition: all 0.3s ease;
        }

        .playback-controls:hover {
            box-shadow: 
                0 0 15px rgba(0, 240, 255, 0.5),
                inset 0 0 20px rgba(0, 240, 255, 0.2);
            border-color: rgba(0, 240, 255, 0.6);
        }

        .playback-controls::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(0, 240, 255, 0.2), transparent);
            animation: shimmer 5s infinite;
            pointer-events: none;
        }

        @keyframes shimmer {
            0% { left: -100%; }
            50% { left: 100%; }
            100% { left: 100%; }
        }

        .speed-selector {
            display: flex;
            align-items: center;
            gap: 5px;
            color: #00f0ff;
            font-size: 14px;
            font-weight: 500;
            letter-spacing: 0.5px;
            text-shadow: 0 0 5px rgba(0, 240, 255, 0.5);
        }

        .speed-selector select {
            background-color: rgba(0, 20, 40, 0.8);
            border: 1px solid rgba(0, 240, 255, 0.5);
            border-radius: 4px;
            color: #00f0ff;
            padding: 4px 8px;
            font-size: 14px;
            outline: none;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 0 8px rgba(0, 240, 255, 0.3);
        }

        .speed-selector select:hover {
            border-color: #00f0ff;
            box-shadow: 0 0 12px rgba(0, 240, 255, 0.7);
            transform: translateY(-1px);
        }

        .speed-selector select option {
            background-color: rgba(0, 20, 40, 0.95);
            color: #00f0ff;
            padding: 5px;
        }

        #auto-play-button {
            background-color: rgba(0, 0, 0, 0.7);
            border: 2px solid #00f0ff;
            border-radius: 50%;
            width: 38px;
            height: 38px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 
                0 0 5px rgba(0, 240, 255, 0.8),
                0 0 8px rgba(0, 240, 255, 0.5),
                0 0 12px rgba(0, 240, 255, 0.3);
            transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            position: relative;
            overflow: hidden;
            pointer-events: auto;
            backdrop-filter: blur(4px);
        }

        #auto-play-button::before {
            content: '';
            position: absolute;
            top: -2px;
            left: -2px;
            right: -2px;
            bottom: -2px;
            border-radius: 50%;
            background: linear-gradient(45deg, #00f0ff, transparent, #00f0ff, transparent);
            z-index: -1;
            animation: borderRotate 3s linear infinite;
            opacity: 0.7;
        }

        @keyframes borderRotate {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        #auto-play-button:hover {
            background-color: rgba(0, 45, 57, 0.8);
            transform: scale(1.15);
            box-shadow: 
                0 0 10px rgba(0, 240, 255, 0.9),
                0 0 15px rgba(0, 240, 255, 0.7),
                0 0 20px rgba(0, 240, 255, 0.5);
        }

        #auto-play-button:active {
            transform: scale(0.95);
            box-shadow: 
                0 0 5px rgba(0, 240, 255, 0.8),
                0 0 8px rgba(0, 240, 255, 0.5);
        }

        #auto-play-button svg {
            width: 22px;
            height: 22px;
            fill: #00f0ff;
            filter: drop-shadow(0 0 2px rgba(0, 240, 255, 0.8));
            transition: all 0.2s ease;
        }

        /* 特定状态样式 */
        #auto-play-button.paused {
            border-color: #ff9800;
            box-shadow: 
                0 0 5px rgba(255, 152, 0, 0.8),
                0 0 8px rgba(255, 152, 0, 0.5),
                0 0 12px rgba(255, 152, 0, 0.3);
        }

        #auto-play-button.paused::before {
            background: linear-gradient(45deg, #ff9800, transparent, #ff9800, transparent);
        }

        #auto-play-button.paused svg {
            fill: #ff9800;
            filter: drop-shadow(0 0 2px rgba(255, 152, 0, 0.8));
        }

        #auto-play-button.paused:hover {
            box-shadow: 
                0 0 10px rgba(255, 152, 0, 0.9),
                0 0 15px rgba(255, 152, 0, 0.7),
                0 0 20px rgba(255, 152, 0, 0.5);
        }

        /* 重写导航按钮样式以修复linter错误 */
        .nav-button {
            background-color: rgba(0, 240, 255, 0.2);
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 0 10px rgba(0, 240, 255, 0.5);
            transition: all 0.3s ease;
            margin: 0 20px;
            pointer-events: auto;
            position: relative;
        }

        .nav-button:hover {
            background-color: rgba(0, 240, 255, 0.3);
            transform: scale(1.1);
        }

        .nav-button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .nav-button svg {
            width: 20px;
            height: 20px;
            fill: #00f0ff;
        }

        .video-preview-content {
            position: relative;
            display: flex;
            align-items: stretch;
            justify-content: space-between;
            margin: 10px 0;
            min-height: 300px;
            gap: 20px;
        }
        
        .video-preview-content img {
            max-width: 100%;
            max-height: 500px;
            border-radius: 4px;
            box-shadow: 0 0 20px rgba(0, 240, 255, 0.3);
            border: 1px solid rgba(0, 240, 255, 0.5);
        }

        .behavior-buttons {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 10px;
            margin: 15px 0;
            overflow-x: auto;
            padding-bottom: 5px;
            max-width: 100%;
        }

        .behavior-button {
            padding: 8px 16px;
            background-color: rgba(84, 112, 198, 0.2);
            color: #e0e0ff;
            border: 1px solid #5470c6;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            white-space: nowrap;
            flex: 0 0 auto;
        }

        .behavior-button.active {
            background-color: rgba(65, 128, 255, 0.6);
            box-shadow: 0 0 10px rgba(0, 240, 255, 0.5);
        }

        .detection-canvas {
            position: absolute;
            top: 0;
            left: 0;
            pointer-events: none;
            width: 100%;
            height: 100%;
            z-index: 10;
        }

        .detection-info {
            margin-top: 10px;
            text-align: center;
            color: #00f0ff;
            font-size: 14px;
            background-color: rgba(0, 240, 255, 0.1);
            padding: 5px 15px;
            border-radius: 15px;
            border: 1px solid rgba(0, 240, 255, 0.3);
            display: inline-block;
        }

        .frame-info {
            text-align: center;
            color: #00f0ff;
            margin-top: 10px;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
        }
        
        .frame-counter {
            background-color: rgba(0, 240, 255, 0.1);
            padding: 5px 15px;
            border-radius: 15px;
            border: 1px solid rgba(0, 240, 255, 0.3);
        }
        
        h1, h2 {
            color: #00f0ff;
            text-shadow: 0 0 10px rgba(0, 240, 255, 0.5);
        }
        
        .loading-image {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 300px;
            color: #00f0ff;
            border: 1px dashed rgba(0, 240, 255, 0.5);
            border-radius: 4px;
            background-color: rgba(20, 20, 40, 0.5);
            max-width: 100%;
            padding: 20px;
            box-sizing: border-box;
            overflow: hidden;
        }
        
        .loading-progress {
            margin-top: 10px;
            font-size: 14px;
            color: #00d0ff;
        }
        
        .preload-status {
            font-size: 12px;
            color: #00d0ff;
            opacity: 0.8;
            margin-top: 5px;
            text-align: center;
        }
        
        .preload-bar {
            width: 200px;
            height: 4px;
            background-color: rgba(0, 240, 255, 0.1);
            border-radius: 2px;
            margin-top: 5px;
            overflow: hidden;
        }
        
        .preload-progress {
            height: 100%;
            background-color: #00f0ff;
            width: 0%;
            transition: width 0.3s ease-in-out;
            box-shadow: 0 0 8px rgba(0, 240, 255, 0.8);
        }
        
        @keyframes pulse {
            0% { opacity: 0.6; }
            50% { opacity: 1; }
            100% { opacity: 0.6; }
        }
        
        /* 全屏模式样式 */
        .fullscreen-mode {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.9);
            z-index: 1000;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        
        .fullscreen-image {
            max-width: 90%;
            max-height: 80vh;
            object-fit: contain;
        }
        
        .fullscreen-controls {
            margin-top: 20px;
            display: flex;
            gap: 15px;
        }
        
        .fullscreen-button {
            background-color: rgba(0, 240, 255, 0.2);
            border: 1px solid #00f0ff;
            color: #00f0ff;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .fullscreen-button:hover {
            background-color: rgba(0, 240, 255, 0.4);
            box-shadow: 0 0 10px #00f0ff;
        }
        
        .close-fullscreen {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: rgba(0, 240, 255, 0.2);
            border: 1px solid #00f0ff;
            color: #00f0ff;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.3s;
            z-index: 100;
        }
        
        .close-fullscreen:hover {
            background-color: rgba(0, 240, 255, 0.4);
            box-shadow: 0 0 10px #00f0ff;
        }

        .preview-left {
            width: 300px;
            background-color: rgba(20, 20, 40, 0.7);
            border-radius: 8px;
            padding: 15px;
            border: 1px solid rgba(65, 128, 255, 0.3);
            box-shadow: 0 0 20px rgba(0, 240, 255, 0.2);
            backdrop-filter: blur(5px);
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .preview-center {
            flex: 1;
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .preview-right {
            width: 300px;
            background-color: rgba(20, 20, 40, 0.7);
            border-radius: 8px;
            padding: 15px;
            border: 1px solid rgba(65, 128, 255, 0.3);
            box-shadow: 0 0 20px rgba(0, 240, 255, 0.2);
            backdrop-filter: blur(5px);
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .behavior-stats {
            margin-bottom: 0;
        }

        .behavior-stats h3, .behavior-pie-chart h3 {
            color: #00f0ff;
            margin-bottom: 15px;
            text-align: center;
            font-size: 16px;
            text-shadow: 0 0 5px rgba(0, 240, 255, 0.5);
            position: relative;
            padding-bottom: 10px;
        }

        .behavior-stats h3::after, .behavior-pie-chart h3::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 50px;
            height: 2px;
            background: linear-gradient(90deg, transparent, #00f0ff, transparent);
        }

        #behavior-stats-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
            max-width: 180px;
            margin: 0 auto;
        }

        .stat-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px;
            background: linear-gradient(135deg, rgba(40, 44, 80, 0.5), rgba(25, 25, 50, 0.8));
            border-radius: 6px;
            color: #e0e0ff;
            font-size: 14px;
            border: 1px solid rgba(0, 240, 255, 0.2);
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            max-width: 180px;
            width: 100%;
            margin-bottom: 8px;
        }

        .stat-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 0 15px rgba(0, 240, 255, 0.3);
            border-color: rgba(0, 240, 255, 0.4);
        }

        .stat-item::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(45deg, transparent, rgba(0, 240, 255, 0.1), transparent);
            transform: translateX(-100%);
            transition: transform 0.5s ease;
        }

        .stat-item:hover::before {
            transform: translateX(100%);
        }

        .stat-item strong {
            color: #99e6ff;
            font-weight: bold;
            text-shadow: 0 0 5px rgba(153, 230, 255, 0.5);
        }

        .stat-item .stat-value {
            font-size: 1.2em;
            font-weight: bold;
            color: #00f0ff;
            text-shadow: 0 0 10px rgba(0, 240, 255, 0.8);
        }

        .stat-item .stat-percentage {
            font-size: 0.9em;
            color: #7adbff;
            opacity: 0.8;
        }

        #current-frame-pie-chart {
            height: 300px;
            position: relative;
        }

        #current-frame-pie-chart::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: radial-gradient(circle at center, rgba(0, 240, 255, 0.1), transparent 70%);
            pointer-events: none;
        }

        .chart-tooltip {
            background-color: rgba(20, 20, 40, 0.9);
            padding: 10px;
            border-radius: 4px;
            color: #e0e0ff;
            font-size: 14px;
            border: 1px solid rgba(0, 240, 255, 0.3);
            box-shadow: 0 0 10px rgba(0, 240, 255, 0.2);
            backdrop-filter: blur(5px);
        }

        /* 添加行为人数统计样式 */
        .behavior-count-summary {
            position: absolute;
            top: 10px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.7);
            color: #00f0ff;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 14px;
            z-index: 100;
            border: 1px solid rgba(0, 240, 255, 0.3);
            box-shadow: 0 0 10px rgba(0, 240, 255, 0.2);
            backdrop-filter: blur(5px);
            text-align: center;
            white-space: nowrap;
            display: none !important; /* 永远隐藏该元素 */
        }

        .timeline-chart {
            width: 100%;
            height: 300px;
            margin-top: 20px;
            overflow: hidden;
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            
            .container {
                padding: 10px;
            }
            
            .frame-view {
                min-height: 200px;
            }
            
            .behavior-buttons {
                flex-direction: row;
                overflow-x: auto;
                justify-content: flex-start;
                padding-bottom: 10px;
            }
            
            .behavior-button {
                flex: 0 0 auto;
                min-width: 100px;
            }
            
            .navigation-controls {
                flex-direction: row;
                overflow-x: auto;
                justify-content: flex-start;
                padding-bottom: 10px;
            }
            
            .timeline-chart, .pie-chart, .radar-chart {
                height: 250px;
            }
            
            .navigation-button {
                padding: 8px 12px;
            }
            
            .stats-panel {
                grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
                padding: 15px 10px;
                gap: 15px;
                overflow-x: auto;
            }
            
            .stat-item {
                padding: 12px;
                min-width: 140px;
            }
            
            .ai-analysis-container {
                flex-direction: column;
            }
            
            .ai-analysis-left, 
            .ai-analysis-right {
                width: 100%;
                padding: 0;
                margin-bottom: 15px;
            }
        }

        .frame-counter-overlay {
            position: absolute;
            top: 10px;
            right: 10px;
            z-index: 10;
            background: rgba(0, 0, 0, 0.6);
            padding: 5px 10px;
            border-radius: 4px;
            border: 1px solid rgba(0, 240, 255, 0.3);
            box-shadow: 0 0 10px rgba(0, 240, 255, 0.2);
            display: flex;
            flex-direction: column;
            align-items: flex-end;
        }
        
        .frame-counter {
            color: #00f0ff;
            font-size: 14px;
            font-weight: 500;
        }

        .time-indicator {
            color: #7adbff;
            font-size: 12px;
            margin-top: 4px;
        }
        
        .video-preview-container {
            position: relative;
        }
        
        .frame-jump-container {
            display: flex;
            justify-content: center;
            margin: 10px 0;
        }
        
        .frame-jump-input {
            display: flex;
            align-items: center;
            background-color: rgba(0, 0, 0, 0.5);
            border-radius: 4px;
            padding: 4px 8px;
            border: 1px solid rgba(0, 240, 255, 0.3);
            box-shadow: 0 0 10px rgba(0, 240, 255, 0.2);
        }
        
        .frame-jump-field {
            background-color: rgba(40, 44, 80, 0.6);
            border: 1px solid rgba(0, 240, 255, 0.5);
            border-radius: 4px;
            color: #00f0ff;
            padding: 6px 10px;
            width: 120px;
            font-size: 14px;
            outline: none;
            transition: all 0.3s;
        }
        
        .frame-jump-field:focus {
            border-color: #00f0ff;
            box-shadow: 0 0 10px rgba(0, 240, 255, 0.5);
        }
        
        .frame-jump-btn {
            background-color: rgba(0, 240, 255, 0.2);
            border: 1px solid rgba(0, 240, 255, 0.5);
            border-radius: 4px;
            color: #00f0ff;
            cursor: pointer;
            margin-left: 8px;
            padding: 6px 12px;
            transition: all 0.3s;
            font-size: 14px;
        }
        
        .frame-jump-btn:hover {
            background-color: rgba(0, 240, 255, 0.4);
            box-shadow: 0 0 10px rgba(0, 240, 255, 0.5);
        }

        .chart-flex-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-top: 20px;
        }
        
        .chart-box {
            flex: 1;
            min-width: 300px;
            background-color: rgba(25, 25, 50, 0.5);
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 0 15px rgba(0, 240, 255, 0.2);
            border: 1px solid rgba(0, 240, 255, 0.3);
            position: relative;
            overflow: hidden;
        }
        
        .chart-box h3 {
            color: #00f0ff;
            text-align: center;
            margin-bottom: 15px;
            font-size: 18px;
            text-shadow: 0 0 8px rgba(0, 240, 255, 0.6);
            position: relative;
            padding-bottom: 10px;
        }
        
        .chart-box h3::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 2px;
            background: linear-gradient(90deg, transparent, #00f0ff, transparent);
        }
        
        .chart-box::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: radial-gradient(circle at 30% 30%, rgba(0, 240, 255, 0.1), transparent 70%);
            pointer-events: none;
        }
        
        @media (max-width: 768px) {
            .chart-flex-container {
                flex-direction: column;
            }
            
            .chart-box {
                width: 100%;
            }
        }

        .control-status {
            color: #00f0ff;
            font-size: 14px;
            font-weight: 500;
            text-shadow: 0 0 5px rgba(0, 240, 255, 0.7);
            letter-spacing: 0.5px;
            white-space: nowrap;
            transition: all 0.3s ease;
        }

        .playback-controls.paused .control-status {
            color: #ff9800;
            text-shadow: 0 0 5px rgba(255, 152, 0, 0.7);
        }

        .frame-info-box {
            background: rgba(0, 0, 0, 0.3);
            border-radius: 8px;
            padding: 12px;
            border: 1px solid rgba(0, 240, 255, 0.2);
        }

        .frame-info-title {
            color: #00f0ff;
            font-size: 16px;
            margin-bottom: 10px;
            text-align: center;
            position: relative;
        }
        
        .frame-info-title::after {
            content: '';
            position: absolute;
            bottom: -5px;
            left: 50%;
            transform: translateX(-50%);
            width: 40px;
            height: 2px;
            background: linear-gradient(90deg, transparent, #00f0ff, transparent);
        }
        
        .frame-info-content {
            color: #e0e0ff;
            font-size: 14px;
            margin-top: 8px;
            line-height: 1.6;
        }
        
        .detection-preview {
            margin-top: 15px;
        }
        
        .mini-preview {
            width: 100%;
            height: 100px;
            background: #000;
            border-radius: 6px;
            border: 1px solid rgba(0, 240, 255, 0.3);
            margin: 10px 0;
            overflow: hidden;
            position: relative;
        }
        
        .mini-preview-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .detection-stats {
            margin-top: 10px;
        }
        
        .stat-mini-item {
            display: flex;
            align-items: center;
            padding: 8px;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 4px;
            margin-bottom: 6px;
            font-size: 13px;
        }
        
        .stat-color {
            width: 12px;
            height: 12px;
            border-radius: 2px;
            margin-right: 8px;
        }
        
        .stat-label {
            flex: 1;
            color: #e0e0ff;
        }
        
        .stat-count {
            color: #00f0ff;
            font-weight: bold;
        }

        /* 响应式调整 */
        @media (max-width: 1200px) {
            .preview-left, .preview-right {
                width: 280px;
            }
        }
        
        @media (max-width: 992px) {
            .video-preview-content {
                flex-direction: column;
            }
            
            .preview-left, .preview-right {
                width: 100%;
                flex-direction: row;
                flex-wrap: wrap;
            }
            
            .frame-info-box {
                width: calc(50% - 10px);
            }
        }
        
        @media (max-width: 768px) {
            .preview-left, .preview-right {
                flex-direction: column;
            }
            
            .frame-info-box {
                width: 100%;
            }
        }

        /* 添加水波纹效果类 */
        .ripple-effect {
            position: relative;
            overflow: hidden;
        }
        
        .ripple-effect:after {
            content: '';
            display: block;
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            pointer-events: none;
            background-image: radial-gradient(circle, rgba(0, 240, 255, 0.3) 10%, transparent 70%);
            background-repeat: no-repeat;
            background-position: 50%;
            transform: scale(10, 10);
            opacity: 0;
            transition: transform 0.5s, opacity 1s;
        }
        
        .ripple-effect.active:after {
            transform: scale(0, 0);
            opacity: 1;
            transition: 0s;
        }
        
        .highlight-change {
            animation: highlight-pulse 1s ease;
        }
        
        @keyframes highlight-pulse {
            0% { text-shadow: 0 0 5px rgba(0, 240, 255, 0.5); }
            50% { text-shadow: 0 0 15px rgba(0, 240, 255, 1); }
            100% { text-shadow: 0 0 5px rgba(0, 240, 255, 0.5); }
        }
        
        .meta-item {
            display: flex;
            justify-content: space-between;
            padding: 6px 10px;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 4px;
            font-size: 13px;
            transition: all 0.3s ease;
        }
        
        .meta-item:hover {
            background: rgba(0, 240, 255, 0.1);
            transform: translateX(3px);
        }
        
        .behavior-count-summary {
            position: absolute;
            top: 10px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.7);
            color: #00f0ff;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 14px;
            z-index: 100;
            border: 1px solid rgba(0, 240, 255, 0.3);
            box-shadow: 0 0 10px rgba(0, 240, 255, 0.2);
            backdrop-filter: blur(5px);
            text-align: center;
            white-space: nowrap;
            display: none !important; /* 永远隐藏该元素 */
        }

        /* 添加迷你饼图样式 */
        .mini-pie-chart {
            width: 100%;
            height: 200px;
            margin: 0 auto;
        }
        
        .stat-mini-item {
            display: none; /* 隐藏原有的列表显示 */
        }
        
        .mini-radar-chart {
            width: 100%;
            height: 200px;
            margin: 0 auto;
        }
        
        .stat-mini-item {
            display: none; /* 隐藏原有的列表显示 */
        }

        .mini-waffle-chart {
            width: 100%;
            height: 200px;
            margin: 0 auto;
        }

        .mini-radar-chart {
            width: 100%;
            height: 200px;
            margin: 0 auto;
        }

        .stat-mini-item {
            display: none; /* 隐藏原有的列表显示 */
        }

        .mini-waffle-chart {
            width: 100%;
            height: 220px; /* 增加高度，从200px改为220px */
            margin: 0 auto;
        }

        /* 雷达图相关样式 */
        .radar-chart {
            width: 100%;
            height: 240px;
            overflow: visible; /* 修改overflow为visible，确保内容不被截断 */
        }

        .chart-container.radar {
            margin-top: 20px;
        }

        /* 小型雷达图 */
        .mini-radar-chart {
            width: 100%;
            height: 220px;
            margin: 0 auto;
            overflow: visible; /* 确保内容不被截断 */
        }

        .mini-waffle-chart {
            width: 100%;
            height: 230px; /* 再次增加高度以确保完全显示 */
            margin: 0 auto;
            overflow: visible; /* 确保内容不被截断 */
        }

        /* 媒体查询：移动设备适配 */
        @media (max-width: 768px) {
            .mini-waffle-chart {
                height: 200px;
            }
            
            .preview-left {
                width: 30%; /* 在小屏上适当调整宽度 */
            }
        }

        /* 媒体查询：平板设备适配 */
        @media (min-width: 769px) and (max-width: 1024px) {
            .mini-waffle-chart {
                height: 220px;
            }
        }

        /* 添加行为平均占比饼图样式 */
        .average-behavior-pie-container {
            padding: 20px;
            background: rgba(10, 20, 40, 0.8);
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 200, 255, 0.1);
            max-width: 1200px;
        }

        .bottom-analysis-container {
            margin-top: 40px;
            width: 100%;
            max-width: 100%;
            padding: 0 5vw;
            box-sizing: border-box;
            position: relative;
            left: 0;
            right: 0;
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            gap: 6vw;
        }

        .analysis-chart-container {
            flex: 1 1 calc(50% - 3vw);
            min-width: 300px;
        }
    </style>
</head>

<body class="content-loading">
    <div style="display: flex; align-items: center; justify-content: center; position: relative;">
        <button class="back-button" id="back-button" style="position: absolute; left: 20px; top: 50%; transform: translateY(-50%);">返回</button>
        <h1 class="page-title" style="margin: 0; color: #00f0ff; font-size: 1.5rem; text-shadow: 0 0 10px rgba(0, 240, 255, 0.7);">课堂行为智能分析平台</h1>
    </div>
    <div class="report-header">
    </div>
    
    <div class="video-preview-container" id="video-preview-container">
        <div class="frame-counter-overlay">
            <span class="frame-counter" id="frame-counter">1/29</span>
        </div>
        <div class="video-preview-content" id="video-preview-content">
            <div class="preview-left">
                <div class="frame-info-box">
                    <div class="frame-info-content">
                        <div id="frame-info-radar-chart" class="mini-waffle-chart" style="height: 240px; width: 100%;"></div>
                    </div>
                </div>
            </div>
            
            <div class="preview-center">
                <div style="position: relative; display: inline-block;">
                    <canvas class="detection-canvas" id="detection-canvas" width="889" height="500"></canvas>
                    <img id="current-image" style="display: block; max-width: 100%; max-height: 500px; border-radius: 4px; box-shadow: rgba(0, 240, 255, 0.3) 0px 0px 20px; border: 1px solid rgba(0, 240, 255, 0.5);" src="">
                </div>
                <div class="loading-image" style="display: none;">
                    <div>图片加载中，请稍候...</div>
                    <div id="loading-details" style="font-size: 12px; margin-top: 5px;">准备中...</div>
                    <div class="preload-bar" style="margin-top: 10px; display: none;">
                        <div class="preload-progress" id="specific-image-progress" style="width: 13%;"></div>
                    </div>
                </div>
            </div>
            
            <div class="preview-right">
                
                <div class="frame-info-box">
                    <div class="frame-info-content">
                        <div id="abnormal-behavior-chart" class="chart" style="height: 180px;"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="frame-navigation">
            <button class="nav-button" id="prev-frame" disabled="">
                <svg viewBox="0 0 24 24">
                    <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"></path>
                </svg>
            </button>
            <button class="nav-button" id="next-frame">
                <svg viewBox="0 0 24 24">
                    <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path>
                </svg>
            </button>
        </div>
        <div class="controls-container" style="display: flex; justify-content: space-between; align-items: center; margin: 10px 0;">
            <div id="behavior-buttons" class="behavior-buttons">
                <button class="behavior-button active" data-behavior="all">全部</button>
                <button class="behavior-button" data-behavior="use_phone">使用手机</button>
                <button class="behavior-button" data-behavior="stand">站立</button>
                <button class="behavior-button" data-behavior="head_on_desk">趴桌</button>
            </div>
            <div class="playback-controls">
                <button id="auto-play-button" class="nav-button paused" onclick="toggleAutoPlay()" title="播放">
                    <svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg>
                </button>
                <span class="control-status">已暂停</span>
                <div class="speed-selector">
                    <span id="play-speed-display"></span>
                </div>
            </div>
            <div class="frame-jump-input">
                <input type="number" id="frame-jump-input" min="1" placeholder="输入帧号 (1-29)" class="frame-jump-field" max="29">
                <button id="frame-jump-button" class="frame-jump-btn">跳转</button>
            </div>
        </div>
        <div id="detection-info" class="detection-info" style="display: none;"></div>
    </div>
    
    <div id="video-report-container" class="skeleton-loading">
        <div class="loading">数据加载中，请稍候...</div>
    </div>

    <script>
        document.body.classList.add('content-loading');
        window.addEventListener('load', function() {
            setTimeout(() => {
                document.body.classList.remove('content-loading');
                document.body.classList.add('content-loaded');
                
                document.querySelectorAll('.skeleton-loading').forEach(el => {
                    el.classList.remove('skeleton-loading');
                });
            }, 200);
        });
    
        function showLoadingNotification(message, duration = 3000) {
            let notification = document.getElementById('loading-notification');
            
            if (!notification) {
                notification = document.createElement('div');
                notification.id = 'loading-notification';
                notification.style.cssText = `
                    position: fixed;
                    bottom: 20px;
                    left: 50%;
                    transform: translateX(-50%);
                    background-color: rgba(0, 0, 0, 0.8);
                    color: #00f0ff;
                    padding: 10px 20px;
                    border-radius: 5px;
                    box-shadow: 0 0 15px rgba(0, 240, 255, 0.5);
                    border: 1px solid rgba(0, 240, 255, 0.3);
                    z-index: 1000;
                    font-size: 14px;
                    opacity: 0;
                    transition: opacity 0.3s;
                `;
                document.body.appendChild(notification);
                
                setTimeout(() => {
                    notification.style.opacity = '1';
                }, 10);
            }
            
            notification.textContent = message;
            
            clearTimeout(notification.fadeOutTimer);
            notification.fadeOutTimer = setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => {
                    if (notification.parentNode) {
                        notification.parentNode.removeChild(notification);
                    }
                }, 300);
            }, duration);
        }
        
        // 新增函数: 更新当前帧的信息面板
        function updateFrameInfoPanel() {
            const frameNumberEl = document.getElementById('current-frame-number');
            const frameTimeEl = document.getElementById('current-frame-time');
            
            if (frameNumberEl) {
                frameNumberEl.textContent = currentImageIndex + 1;
            }
            
            if (frameTimeEl) {
                frameTimeEl.textContent = frameToVideoTime(currentImageIndex);
            }
            
            // 更新检测总数
            updateDetectionCountDisplay();
            
            // 更新帧信息雷达图
            updateFrameInfoRadarChart();
            
            // 更新行为饼图
            updateBehaviorPieChart();
        }
        
        // 新增函数: 更新检测总数显示
        function updateDetectionCountDisplay() {
            const detectionCountEl = document.getElementById('detection-count');
            if (!detectionCountEl) return;
            
            let count = 0;
            
            // 尝试从当前帧的检测结果获取总数
            if (detectionResultCache[currentImageIndex]) {
                const detections = detectionResultCache[currentImageIndex].detections;
                if (Array.isArray(detections)) {
                    count = detections.length;
                } else if (detections) {
                    count = 1;
                }
            }
            // 如果没有检测结果，尝试从图像处理结果获取
            else if (imageProcessResults[currentImageIndex]) {
                const results = imageProcessResults[currentImageIndex];
                Object.values(results).forEach(boxes => {
                    if (Array.isArray(boxes)) {
                        count += boxes.length;
                    }
                });
            }
            
            detectionCountEl.textContent = count;
        }
        
        // 新增函数: 更新行为统计面板
        function updateBehaviorSummary() {
            const summaryContainer = document.getElementById('frame-analysis-summary');
            if (!summaryContainer) return;
            
            // 清空容器内容
            summaryContainer.innerHTML = '';
            
            if (imageProcessResults[currentImageIndex]) {
                const results = imageProcessResults[currentImageIndex];
                let behaviorCounts = {};
                let totalCount = 0;
                
                // 行为名称映射
                const behaviorNames = {
                    "use_phone": "使用手机",
                    "stand": "站立",
                    "head_on_desk": "趴桌",
                    "look_up": "抬头"
                };
                const behaviorColors = {
                    "use_phone": "#33FF57",
                    "stand": "#3357FF",
                    "head_on_desk": "#9C27B0",
                    "look_up": "#FF4081"
                };
                
                // 计算每种行为的检测框数量
                Object.entries(results).forEach(([behavior, boxes]) => {
                    if (behavior === 'yolo_model_output' && Array.isArray(boxes)) {
                        totalCount = boxes.length;
                    } else if (behavior !== 'yolo_model_output' && Array.isArray(boxes)) {
                        const name = behaviorNames[behavior] || behavior;
                        behaviorCounts[behavior] = {
                            name: name,
                            count: boxes.length,
                            color: behaviorColors[behavior] || '#FFFFFF'
                        };
                    }
                });
                
                // 如果没有检测到任何行为
                if (Object.keys(behaviorCounts).length === 0) {
                    const emptyNotice = document.createElement('div');
                    emptyNotice.style.textAlign = 'center';
                    emptyNotice.style.padding = '10px';
                    emptyNotice.style.color = '#7adbff';
                    emptyNotice.textContent = '未检测到行为';
                    summaryContainer.appendChild(emptyNotice);
                }
            } else {
                const loadingNotice = document.createElement('div');
                loadingNotice.style.textAlign = 'center';
                loadingNotice.style.padding = '10px';
                loadingNotice.style.color = '#7adbff';
                loadingNotice.textContent = '等待数据加载...';
                summaryContainer.appendChild(loadingNotice);
            }
        }
        
        // 新增函数：更新行为统计饼图
        function updateBehaviorSummaryPieChart(behaviorCounts, totalCount) {
            const chartDom = document.getElementById('behavior-summary-pie-chart');
            if (!chartDom || !window.echarts) return;
            
            // 初始化图表
            let myChart = echarts.getInstanceByDom(chartDom);
            if (!myChart) {
                myChart = echarts.init(chartDom);
            }
            
            // 准备饼图数据
            const data = Object.entries(behaviorCounts).map(([key, item]) => ({
                value: item.count,
                name: item.name,
                itemStyle: {
                    color: item.color
                }
            }));
            
            // 饼图配置
            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}: {c}人 ({d}%)',
                    backgroundColor: 'rgba(20, 20, 40, 0.9)',
                    borderColor: 'rgba(0, 240, 255, 0.3)',
                    textStyle: {
                        color: '#e0e0ff'
                    }
                },
                legend: {
                    orient: 'horizontal',
                    bottom: 0,
                    itemWidth: 12,
                    itemHeight: 12,
                    textStyle: {
                        color: '#e0e0ff',
                        fontSize: 10
                    }
                },
                series: [
                    {
                        name: '行为统计',
                        type: 'pie',
                        radius: ['35%', '70%'],
                        center: ['50%', '45%'],
                        avoidLabelOverlap: true,
                        itemStyle: {
                            borderRadius: 6,
                            borderColor: '#0a0a1a',
                            borderWidth: 2
                        },
                        label: {
                            show: false
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: 12,
                                fontWeight: 'bold',
                                formatter: '{b}: {c}人\n{d}%',
                                color: '#e0e0ff',
                                textShadow: '0 0 5px rgba(0, 240, 255, 0.5)'
                            },
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 240, 255, 0.5)'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: data
                    }
                ]
            };
            
            // 如果没有数据，显示无数据提示
            if (data.length === 0) {
                option.title = {
                    text: '无可用数据',
                    textStyle: {
                        color: '#e0e0ff'
                    },
                    left: 'center',
                    top: 'center'
                };
            }
            
            // 设置图表选项
            myChart.setOption(option);
            
            // 响应窗口大小变化
            window.addEventListener('resize', () => {
                myChart.resize();
            });
        }
        
        // 新增函数: 更新异常行为统计
        function updateAbnormalBehaviors() {
            const phoneCountEl = document.getElementById('phone-usage-count');
            const standingCountEl = document.getElementById('standing-count');
            const deskHeadCountEl = document.getElementById('desk-head-count');
            
            let phoneCount = 0;
            let standingCount = 0;
            let deskHeadCount = 0;
            let lookUpCount = 0;
            
            if (imageProcessResults[currentImageIndex]) {
                const results = imageProcessResults[currentImageIndex];
                
                // 统计各类异常行为
                if (results['use_phone'] && Array.isArray(results['use_phone'])) {
                    phoneCount = results['use_phone'].length;
                }
                
                if (results['stand'] && Array.isArray(results['stand'])) {
                    standingCount = results['stand'].length;
                }
                
                if (results['head_on_desk'] && Array.isArray(results['head_on_desk'])) {
                    deskHeadCount = results['head_on_desk'].length;
                }
                
                if (results['look_up'] && Array.isArray(results['look_up'])) {
                    lookUpCount = results['look_up'].length;
                }
            }
            
            // 更新显示
            if (phoneCountEl) phoneCountEl.textContent = phoneCount;
            if (standingCountEl) standingCountEl.textContent = standingCount;
            if (deskHeadCountEl) deskHeadCountEl.textContent = deskHeadCount;
            
            // 高亮异常行为数量（如果数量大于0）
            if (phoneCountEl) {
                phoneCountEl.style.color = phoneCount > 0 ? '#FF5722' : '#00f0ff';
                phoneCountEl.style.textShadow = phoneCount > 0 ? '0 0 8px rgba(255, 87, 34, 0.7)' : '';
            }
            
            if (standingCountEl) {
                standingCountEl.style.color = standingCount > 0 ? '#FF5722' : '#00f0ff';
                standingCountEl.style.textShadow = standingCount > 0 ? '0 0 8px rgba(255, 87, 34, 0.7)' : '';
            }
            
            if (deskHeadCountEl) {
                deskHeadCountEl.style.color = deskHeadCount > 0 ? '#FF5722' : '#00f0ff';
                deskHeadCountEl.style.textShadow = deskHeadCount > 0 ? '0 0 8px rgba(255, 87, 34, 0.7)' : '';
            }
            
            // 更新异常行为柱状图
            updateAbnormalBehaviorChart(phoneCount, standingCount, deskHeadCount, lookUpCount);
        }
        
        // 新增函数: 更新异常行为柱状图
        function updateAbnormalBehaviorChart(phoneCount, standingCount, deskHeadCount, lookUpCount) {
            const chartDom = document.getElementById('abnormal-behavior-chart');
            if (!chartDom || !window.echarts) return;
            
            // 检查是否已经初始化过图表
            let myChart = echarts.getInstanceByDom(chartDom);
            if (!myChart) {
                myChart = echarts.init(chartDom);
            }
            
            // 如果没有传入参数，尝试从全局数据中获取
            if (phoneCount === undefined || standingCount === undefined || 
                deskHeadCount === undefined || lookUpCount === undefined) {
                
                // 尝试从当前帧的检测结果获取各类行为数量
                if (imageProcessResults[currentImageIndex]) {
                    const results = imageProcessResults[currentImageIndex];
                    phoneCount = (results.use_phone && Array.isArray(results.use_phone)) ? results.use_phone.length : 0;
                    standingCount = (results.stand && Array.isArray(results.stand)) ? results.stand.length : 0;
                    deskHeadCount = (results.head_on_desk && Array.isArray(results.head_on_desk)) ? results.head_on_desk.length : 0;
                    lookUpCount = (results.look_up && Array.isArray(results.look_up)) ? results.look_up.length : 0;
                } else {
                    // 设置默认值
                    phoneCount = phoneCount || 0;
                    standingCount = standingCount || 0;
                    deskHeadCount = deskHeadCount || 0;
                    lookUpCount = lookUpCount || 0;
                }
            }
            
            // 准备柱状图数据，只包含人数大于0的行为
            const data = [];
            
            if (lookUpCount > 0) {
                data.push({ name: '抬头', value: lookUpCount });
            }
            
            if (phoneCount > 0) {
                data.push({ name: '使用手机', value: phoneCount });
            }
            
            if (standingCount > 0) {
                data.push({ name: '站立', value: standingCount });
            }
            
            if (deskHeadCount > 0) {
                data.push({ name: '趴桌', value: deskHeadCount });
            }
            
            // 显示提示信息，如果没有异常行为
            if (data.length === 0) {
                myChart.setOption({
                    title: {
                        text: '当前帧无异常行为',
                        textStyle: {
                            color: '#e0e0ff',
                            fontSize: 14
                        },
                        left: 'center',
                        top: 'center'
                    },
                    xAxis: { show: false },
                    yAxis: { show: false },
                    series: [],
                    backgroundColor: 'transparent'
                });
                
                // 更新摘要显示
                const summaryEl = document.getElementById('abnormal-behavior-summary');
                if (summaryEl) {
                    summaryEl.style.display = 'none';
                }
                
                return;
            }
            
            // 更新摘要显示
            const summaryEl = document.getElementById('abnormal-behavior-summary');
            if (summaryEl) {
                summaryEl.style.display = 'block';
                
                // 更新各行为计数
                const phoneEl = document.getElementById('phone-usage-count');
                const standingEl = document.getElementById('standing-count');
                const deskHeadEl = document.getElementById('desk-head-count');
                
                if (phoneEl) phoneEl.textContent = phoneCount;
                if (standingEl) standingEl.textContent = standingCount;
                if (deskHeadEl) deskHeadEl.textContent = deskHeadCount;
                
                // 设置颜色
                if (phoneEl) phoneEl.style.color = phoneCount > 0 ? 'rgb(255, 87, 34)' : 'rgb(0, 240, 255)';
                if (standingEl) standingEl.style.color = standingCount > 0 ? 'rgb(255, 87, 34)' : 'rgb(0, 240, 255)';
                if (deskHeadEl) deskHeadEl.style.color = deskHeadCount > 0 ? 'rgb(255, 87, 34)' : 'rgb(0, 240, 255)';
                
                // 添加文本阴影
                if (phoneEl) phoneEl.style.textShadow = phoneCount > 0 ? 'rgba(255, 87, 34, 0.7) 0px 0px 8px' : 'none';
                if (standingEl) standingEl.style.textShadow = standingCount > 0 ? 'rgba(255, 87, 34, 0.7) 0px 0px 8px' : 'none';
                if (deskHeadEl) deskHeadEl.style.textShadow = deskHeadCount > 0 ? 'rgba(255, 87, 34, 0.7) 0px 0px 8px' : 'none';
            }
            
            // 柱状图配置
            const option = {
                backgroundColor: 'transparent',
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '10%',
                    top: '10%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: data.map(item => item.name),
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.3)'
                        }
                    },
                    axisLabel: {
                        color: '#e0e0ff',
                        fontSize: 12,
                        rotate: 0,
                        interval: 0 // 强制显示所有标签
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '人数',
                    nameTextStyle: {
                        color: '#00f0ff',
                        fontSize: 10
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.3)'
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.1)'
                        }
                    },
                    axisLabel: {
                        color: '#e0e0ff',
                        fontSize: 10
                    },
                    minInterval: 1, // 确保Y轴刻度为整数
                    max: phoneCount + standingCount + deskHeadCount + lookUpCount || 10 // 设置最大值为总人数，如果总人数为0则使用10作为默认值
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: '{b}: {c}人',
                    backgroundColor: 'rgba(20, 20, 40, 0.9)',
                    borderColor: 'rgba(0, 240, 255, 0.3)',
                    textStyle: {
                        color: '#e0e0ff'
                    }
                },
                series: [
                    {
                        type: 'bar',
                        data: data.map(item => ({
                            value: item.value,
                            itemStyle: {
                                color: getBehaviorColor(item.name),
                                borderRadius: [5, 5, 0, 0]
                            }
                        })),
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(255, 255, 255, 0.05)',
                            borderRadius: [5, 5, 0, 0]
                        },
                        barWidth: '50%',
                        label: {
                            show: true,
                            position: 'top',
                            color: '#e0e0ff',
                            fontSize: 12,
                            formatter: '{c}' // 只显示数值
                        },
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 15,
                                shadowColor: 'rgba(0, 240, 255, 0.5)'
                            }
                        }
                    }
                ],
                // 设置明显的动画效果，确保用户能注意到图表更新
                animationDuration: 500,
                animationEasing: 'bounceOut',
                animation: true
            };
            
            // 设置图表选项并强制更新
            myChart.setOption(option, true);
            
            // 在设置完选项后再次调用刷新方法以确保图表更新
            myChart.clear();
            myChart.setOption(option, true);
            
            // 响应窗口大小变化
            window.addEventListener('resize', () => {
                if (myChart && !myChart.isDisposed()) {
                    myChart.resize();
                }
            });
        }
        
        document.addEventListener('DOMContentLoaded', () => {
            const videoID = localStorage.getItem('video_id');
            const userToken = localStorage.getItem('token');
            
            if (!userToken) {
                showLoadingNotification('请先登录', 3000);
                setTimeout(() => {
                    window.location.href = FRONT_END_DOMAIN + '/login_register_page';
                }, 3000);
                return;
            }

            // 初始化播放按钮状态
            updatePlayButton();

            let rawSeconds = localStorage.getItem('seconds');
            // console.log('localStorage中的原始seconds值:', rawSeconds);
            
            if (!rawSeconds) {
                throw new Error('seconds参数未设置');
            }
            
            const seconds = Number(rawSeconds);
            if (isNaN(seconds)) {
                throw new Error('seconds参数不是有效数字');
            }
            
            if (seconds <= 0) {
                throw new Error('seconds参数必须大于0');
            }
            
            window.seconds = seconds;
            
            // console.log('最终使用的seconds参数值:', window.seconds, '类型:', typeof window.seconds);
            
            showLoadingNotification(`视频时间间隔设置为: ${window.seconds}秒/帧`, 3000);
            
            // 更新帧间隔提示文本
            const frameJumpHint = document.querySelector('.frame-jump-input span');
            if (frameJumpHint) {
                frameJumpHint.textContent = `帧号 × 间隔(${window.seconds}秒) = 视频时间`;
            }
            
            checkToken(BACKEND_DOMAIN, userToken)
                .then(isTokenValid => {
                    if (!isTokenValid) {
                        showLoadingNotification('登录已过期，请重新登录', 3000);
                        setTimeout(() => {
                            window.location.href = FRONT_END_DOMAIN + '/login_register_page';
                        }, 3000);
                        return;
                    }

                    document.getElementById('back-button').addEventListener('click', () => {
                        window.location.href = FRONT_END_DOMAIN + '/video_processing_result_page';
                    });
                    
                    if (!seconds || isNaN(seconds) || seconds <= 0) {
                        // console.log('使用备选方案：设置默认seconds值为1');
                        localStorage.setItem('seconds', '1');
                        window.seconds = 1;
                    } else {
                        window.seconds = seconds;
                    }
                    
                    loadImagePaths();

                    getVideoProcessedResultApi(BACKEND_DOMAIN, userToken, videoID)
                        .then(response => {
                            try {
                                // console.log('原始响应数据:', response);
                                let processedResponse = response;
                                
                                // 初始化默认空响应对象，防止后续处理出错
                                if (!processedResponse) {
                                    processedResponse = { TF: 'F', message: '服务器返回空数据', processed_result: [] };
                                    showLoadingNotification('服务器返回空数据，使用默认值显示', 3000);
                                }
                                
                                if (typeof response === 'string') {
                                    try {
                                        processedResponse = JSON.parse(response);
                                    } catch (parseError) {
                                        console.error('JSON解析错误:', parseError);
                                        console.error('解析失败的字符串:', response);
                                        processedResponse = { TF: 'F', message: 'JSON解析错误', processed_result: [] };
                                        showLoadingNotification('数据格式错误，使用默认值显示', 3000);
                                    }
                                }
                                
                                if (!processedResponse || typeof processedResponse !== 'object') {
                                    console.error('无效的响应类型:', typeof processedResponse);
                                    processedResponse = { TF: 'F', message: '无效响应类型', processed_result: [] };
                                    showLoadingNotification('无效响应类型，使用默认值显示', 3000);
                                }
                                
                                if (processedResponse.TF === 'F') {
                                    showLoadingNotification(processedResponse.message || '服务器返回错误', 3000);
                                    // 创建一个最小可用的数据对象，防止后续渲染失败
                                    if (!processedResponse.processed_result) {
                                        processedResponse.processed_result = [];
                                    }
                                }
                                
                                // 确保processed_result是可用的
                                if (!processedResponse.processed_result) {
                                    processedResponse.processed_result = [];
                                    showLoadingNotification('处理结果为空，使用默认值显示', 3000);
                                }
                                
                                if (typeof processedResponse.processed_result === 'string') {
                                    try {
                                        processedResponse.processed_result = JSON.parse(processedResponse.processed_result);
                                    } catch (e) {
                                        console.warn('processed_result解析失败，尝试作为数组处理');
                                        // 尝试替换转义引号后再解析
                                        try {
                                            const cleanString = processedResponse.processed_result
                                                .replace(/\\"/g, '"')
                                                .replace(/"{/g, '{')
                                                .replace(/}"/g, '}');
                                            processedResponse.processed_result = JSON.parse(cleanString);
                                        } catch (innerError) {
                                            // 如果仍然解析失败，使用默认值
                                            console.error('二次解析失败:', innerError);
                                            processedResponse.processed_result = [];
                                        }
                                    }
                                }
                                
                                // 确保processed_result是数组
                                if (!Array.isArray(processedResponse.processed_result)) {
                                    processedResponse.processed_result = [processedResponse.processed_result];
                                }
                                
                                if (Array.isArray(processedResponse.processed_result)) {
                                    processedResponse.processed_result = processedResponse.processed_result.map((item, index) => {
                                        if (typeof item === 'string') {
                                            try {
                                                return JSON.parse(item);
                                            } catch (e) {
                                                console.warn(`数组索引 ${index} 的JSON解析失败:`, item);
                                                // 尝试替换转义引号后再解析
                                                try {
                                                    const cleanString = item
                                                        .replace(/\\"/g, '"')
                                                        .replace(/"{/g, '{')
                                                        .replace(/}"/g, '}');
                                                    return JSON.parse(cleanString);
                                                } catch (innerError) {
                                                    // 如果仍然解析失败，返回一个默认对象
                                                    return { frame_number: index, detections: [] };
                                                }
                                            }
                                        }
                                        return item || { frame_number: index, detections: [] };
                                    });
                                }
                                
                                // console.log('处理后的响应数据:', processedResponse);
                                // 原有代码继续...
                                
                                // 生成行为按钮
                                generateBehaviorButtons(processedResponse);
                                
                                // 渲染视频分析报告
                                renderVideoReport(processedResponse);
                                
                                // 尝试加载第一帧的检测结果
                                loadFirstFrameResult(processedResponse, videoID, userToken);
                            } catch (error) {
                                console.error('解析视频处理结果时出错:', error);
                                showLoadingNotification('数据格式错误，请稍后重试', 3000);
                                document.getElementById('video-report-container').innerHTML = '<div class="error-message"><p>数据格式错误</p><p>可能原因：</p><ul style="text-align: left; display: inline-block;"><li>服务器返回数据格式不正确</li><li>网络传输过程中数据损坏</li><li>数据解析失败</li></ul><p>请刷新页面重试或联系管理员</p></div>';
                            }
                        })
                        .catch(error => {
                            console.error('获取视频处理结果时出错:', error);
                            showLoadingNotification('视频数据加载失败，请稍后重试', 3000);
                            document.getElementById('video-report-container').innerHTML = '<div class="error-message"><p>视频数据加载失败</p><p>可能原因：</p><ul style="text-align: left; display: inline-block;"><li>网络连接问题</li><li>后端服务未正确响应</li><li>数据格式不兼容</li></ul><p>请刷新页面重试或联系管理员</p></div>';
                        });
                })
                .catch(error => {
                    console.error('检查token时出错:', error);
                    showLoadingNotification('系统错误，请重新登录', 3000);
                    setTimeout(() => {
                        window.location.href = FRONT_END_DOMAIN + '/login_register_page';
                    }, 3000);
                });

            // 添加导航按钮事件监听
            document.getElementById('prev-frame').addEventListener('click', () => navigateFrames(-1));
            document.getElementById('next-frame').addEventListener('click', () => navigateFrames(1));
            
            // 添加跳转按钮事件监听
            document.getElementById('frame-jump-button').addEventListener('click', () => {
                const frameInput = document.getElementById('frame-jump-input');
                const frameNumber = parseInt(frameInput.value);
                if (!isNaN(frameNumber)) {
                    jumpToFrame(frameNumber);
                }
            });
            
            // 为跳转输入框添加回车键事件监听
            document.getElementById('frame-jump-input').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    const frameNumber = parseInt(e.target.value);
                    if (!isNaN(frameNumber)) {
                        jumpToFrame(frameNumber);
                    }
                }
            });
            
            // 初始化预加载状态显示
            const preloadStatus = document.querySelector('.preload-status');
            const preloadBar = document.querySelector('.preload-bar');
            if (preloadStatus && preloadBar) {
                preloadStatus.style.display = forceFullPreload ? 'block' : 'none';
                preloadBar.style.display = forceFullPreload ? 'block' : 'none';
            }
            
            // 添加键盘导航支持
            document.addEventListener('keydown', (e) => {
                if (e.key === 'ArrowLeft') {
                    navigateFrames(-1);
                } else if (e.key === 'ArrowRight') {
                    navigateFrames(1);
                } else if (e.key === ' ' || e.key === 'Space') {
                    // 空格键切换播放/暂停
                    toggleAutoPlay();
                    e.preventDefault(); // 防止页面滚动
                }
            });
        });
        
        function generateBehaviorButtons(data) {
            // 从localStorage获取token和video_id
            const videoID = localStorage.getItem('video_id');
            const userToken = localStorage.getItem('token');
            
            if (!videoID || !userToken) {
                console.warn('缺少必要参数，无法获取行为类别');
                return;
            }
            
            // 先清空按钮容器
            const buttonContainer = document.getElementById('behavior-buttons');
            buttonContainer.innerHTML = '';
            
            // 使用getVideoClassesApi获取视频的行为类别
            getVideoClassesApi(BACKEND_DOMAIN, userToken, videoID)
                .then(classes => {
                    if (!classes || classes.length === 0) {
                        console.warn('未找到行为类别');
                        return;
                    }
                    
                    // 确保classes中包含yolo_model_output（用于内部处理）
                    // 但不再为yolo_model_output创建单独的按钮
                    if (!classes.includes('yolo_model_output')) {
                        classes.push('yolo_model_output');
                    }
                    
                    // 创建"全部"按钮
                    const allButton = document.createElement('button');
                    allButton.className = 'behavior-button active';
                    allButton.dataset.behavior = 'all';
                    allButton.textContent = '全部';
                    allButton.addEventListener('click', function() {
                        setActiveBehaviorFilter(this);
                    });
                    buttonContainer.appendChild(allButton);
                    
                    // 行为类别的中文映射
                    const behaviorMap = {
                        "look_up": "抬头",
                        "use_phone": "使用手机",
                        "stand": "站立",
                        "head_on_desk": "趴桌"
                        // 移除 "yolo_model_output": "所有检测框" 映射
                    };
                    
                    // 为每种行为创建按钮，只有在获取到的classes中的行为才会被显示
                    // 排除yolo_model_output，因为它与"全部"按钮功能重复
                    classes.forEach(behavior => {
                        // 跳过yolo_model_output，不为它创建单独的按钮
                        if (behavior === 'yolo_model_output') {
                            return;
                        }
                        
                        const button = document.createElement('button');
                        button.className = 'behavior-button';
                        button.dataset.behavior = behavior;
                        // 显示中文名称（如果有映射）或原始名称
                        button.textContent = behaviorMap[behavior] || behavior;
                        button.addEventListener('click', function() {
                            setActiveBehaviorFilter(this);
                        });
                        buttonContainer.appendChild(button);
                    });
                    
                    // 自动应用"全部"按钮的行为过滤
                    applyBehaviorFilter('all');
                })
                .catch(error => {
                    console.error('获取视频行为类别时出错:', error);
                    
                    // 退回到原来的方法，从处理结果中提取行为类型
                    fallbackExtractBehaviors(data);
                });
        }

        // 保留原来的行为提取方法作为后备方案
        function fallbackExtractBehaviors(data) {
            // 从视频处理结果中获取所有行为类型
            const behaviors = extractBehaviors(data);
            
            if (!behaviors || behaviors.length === 0) {
                console.warn('未找到行为类型');
                return;
            }
            
            // 确保behaviors中包含yolo_model_output
            if (!behaviors.includes('yolo_model_output')) {
                behaviors.push('yolo_model_output');
            }
            
            // 获取行为按钮容器
            const buttonContainer = document.getElementById('behavior-buttons');
            buttonContainer.innerHTML = '';
            
            // 创建"全部"按钮
            const allButton = document.createElement('button');
            allButton.className = 'behavior-button active';
            allButton.dataset.behavior = 'all';
            allButton.textContent = '全部';
            allButton.addEventListener('click', function() {
                setActiveBehaviorFilter(this);
            });
            buttonContainer.appendChild(allButton);
            
            // 行为类别的中文映射
            const behaviorMap = {
                "look_up": "抬头",
                "use_phone": "使用手机",
                "stand": "站立",
                "head_on_desk": "趴桌",
                "yolo_model_output": "所有检测框"
            };
            
            // 为每种行为创建按钮
            behaviors.forEach(behavior => {
                const button = document.createElement('button');
                button.className = 'behavior-button';
                button.dataset.behavior = behavior;
                // 显示中文名称（如果有映射）或原始名称
                button.textContent = behaviorMap[behavior] || behavior;
                button.addEventListener('click', function() {
                    setActiveBehaviorFilter(this);
                });
                buttonContainer.appendChild(button);
            });
            
            // 自动应用"全部"按钮的行为过滤
            applyBehaviorFilter('all');
        }
        
        function extractBehaviors(data) {
            // 尝试从processed_result中提取行为类型
            if (!data || !data.processed_result) return [];
            
            const behaviors = new Set();
            
            try {
                // 如果是数组，遍历每个结果
                if (Array.isArray(data.processed_result)) {
                    data.processed_result.forEach(result => {
                        extractBehaviorsFromResult(result, behaviors);
                    });
                } else {
                    // 如果是单个对象
                    extractBehaviorsFromResult(data.processed_result, behaviors);
                }
            } catch (error) {
                console.error('提取行为类型时出错:', error);
            }
            
            return Array.from(behaviors);
        }
        
        function extractBehaviorsFromResult(result, behaviorsSet) {
            // 从单个结果中提取行为
            if (!result) return;
            
            try {
                // 如果结果中有detections字段
                if (result.detections) {
                    if (Array.isArray(result.detections)) {
                        result.detections.forEach(detection => {
                            if (detection && detection.label) {
                                behaviorsSet.add(detection.label);
                            }
                        });
                    } else if (result.detections.label) {
                        behaviorsSet.add(result.detections.label);
                    }
                }
                
                // 如果结果有子级结果
                if (result.frames) {
                    result.frames.forEach(frame => {
                        extractBehaviorsFromResult(frame, behaviorsSet);
                    });
                }
                
                // 标准行为类型如果没有从数据中提取到
                const standardBehaviors = [];
                standardBehaviors.forEach(behavior => {
                    behaviorsSet.add(behavior);
                });
            } catch (error) {
                console.warn('从单个结果提取行为时出错:', error);
            }
        }
        
        function setActiveBehaviorFilter(buttonElement) {
            // 移除其他按钮的active状态
            document.querySelectorAll('.behavior-button').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // 设置当前按钮为active
            buttonElement.classList.add('active');
            
            // 应用行为过滤器
            const behavior = buttonElement.dataset.behavior;
            applyBehaviorFilter(behavior);
        }
        
        function applyBehaviorFilter(behavior) {
            // 获取当前图片的处理结果
            const processResult = imageProcessResults[currentImageIndex];
            if (!processResult) {
                // console.log(`图片${currentImageIndex+1}的处理结果尚未获取`);
                return;
            }
            
            // 绘制检测框
            drawDetectionBoxes(processResult, behavior);
            
            // 更新显示的文本
            updateDetectionInfoText(processResult, behavior);
        }
        
        // 新增函数：更新检测信息文本
        function updateDetectionInfoText(processResult, behavior) {
            const detectionInfo = document.getElementById('detection-info');
            if (!detectionInfo) return;
            
            detectionInfo.style.display = 'none';
        }
        
        function renderVideoReport(data) {
            const container = document.getElementById('video-report-container');
            
            // 清空现有内容
            container.innerHTML = '';
            
            try {
                // 如果没有有效数据，显示错误信息
                if (!data || !data.processed_result) {
                    container.innerHTML = '<div class="error-message">没有可用的视频分析数据</div>';
                    return;
                }
                
                // 处理新的API返回的数据结构
                const processedData = processVideoData(data);
                console.log('处理后的视频数据:', processedData);
                
                // 创建行为趋势图表
                const trendChartContainer = document.createElement('div');
                trendChartContainer.className = 'chart-container';
                trendChartContainer.innerHTML = `
                    <h2>行为趋势变化</h2>
                    <div class="chart-tip">展示课堂中各类行为随时间的变化趋势</div>
                    <div class="chart" id="trend-chart"></div>
                    <div class="legend-tip" style="text-align: center; color: #00ffff; font-size: 0.9em; margin-top: 5px; opacity: 0.8;">提示：点击上方图例可显示/隐藏对应折线</div>
                `;
                container.appendChild(trendChartContainer);
                
                // 创建AI分析容器
                const aiAnalysisContainer = document.createElement('div');
                aiAnalysisContainer.className = 'ai-analysis-container';
                aiAnalysisContainer.innerHTML = `
                    <div class="ai-analysis-left">
                        <div class="ai-analysis-header">
                            <h2>小智智能分析</h2>
                            <button class="analysis-btn" id="regenerate-analysis">重新分析</button>
                        </div>
                        <div class="ai-analysis-content" id="ai-analysis-content">
                            <div class="ai-loading">AI正在分析课堂状态，请稍候...</div>
                        </div>
                    </div>
                    <div class="ai-analysis-right">
                        <div class="ai-analysis-header">
                            <h2>课堂行为雷达图</h2>
                        </div>
                        <div class="pie-chart" id="radar-chart"></div>
                    </div>
                `;
                container.appendChild(aiAnalysisContainer);
                
                // 初始化图表
                initTrendChart(processedData);
                initRadarChart(processedData);
                generateAIAnalysis(processedData);
                
                // 设置重新分析按钮点击事件
                document.getElementById('regenerate-analysis').addEventListener('click', () => {
                    generateAIAnalysis(processedData);
                });
            } catch (error) {
                console.error('渲染视频报告时出错:', error);
                container.innerHTML = '<div class="error-message">渲染分析报告时出错，请刷新页面重试</div>';
            }
        }
        
        function processVideoData(data) {
            console.log('处理视频数据:', data);
            if (!data || !data.processed_result) {
                console.error('无效的视频数据格式');
                return { processed_result: [] };
            }
            
            try {
                // 检查是否为新的API返回格式（数组的数组）
                if (Array.isArray(data.processed_result) && data.processed_result.length > 0 && Array.isArray(data.processed_result[0])) {
                    const processedResult = [];
                    
                    // 获取所有时间点
                    const timePointsSet = new Set();
                    data.processed_result.forEach(categoryData => {
                        if (Array.isArray(categoryData)) {
                            categoryData.forEach(item => {
                                if (item && item.时间点 !== undefined) {
                                    timePointsSet.add(item.时间点);
                                }
                            });
                        }
                    });
                    
                    // 转换为排序后的数组
                    const timePoints = Array.from(timePointsSet).sort((a, b) => a - b);
                    
                    // 首先创建每个时间点的基本结构
                    timePoints.forEach(timePoint => {
                        const timePointResult = {
                            frame_number: timePoint,
                            detections: []
                        };
                        
                        // 遍历每个行为类别的数据
                        data.processed_result.forEach(categoryData => {
                            if (Array.isArray(categoryData)) {
                                const item = categoryData.find(item => item.时间点 === timePoint);
                                if (item) {
                                    // 检查并添加每种可能的行为
                                    if (item.总人数 !== undefined) {
                                        timePointResult.detections.push({
                                            label: '总人数',
                                            count: item.总人数
                                        });
                                    }
                                    
                                    if (item.站立人数 !== undefined) {
                                        timePointResult.detections.push({
                                            label: '站立',
                                            count: item.站立人数
                                        });
                                    }
                                    
                                    if (item.使用手机人数 !== undefined) {
                                        timePointResult.detections.push({
                                            label: '使用手机',
                                            count: item.使用手机人数
                                        });
                                    }
                                    
                                    if (item.趴桌人数 !== undefined) {
                                        timePointResult.detections.push({
                                            label: '趴桌',
                                            count: item.趴桌人数
                                        });
                                    }
                                    
                                    if (item.抬头人数 !== undefined) {
                                        timePointResult.detections.push({
                                            label: '抬头',
                                            count: item.抬头人数
                                        });
                                    }
                                    
                                    // 添加其他可能的行为类型
                                    // 遍历item的所有属性，查找其他可能的行为类型
                                    Object.keys(item).forEach(key => {
                                        // 跳过已处理的属性和时间点
                                        if (key !== '时间点' && key !== '总人数' && key !== '站立人数' && 
                                            key !== '使用手机人数' && key !== '趴桌人数' && key !== '抬头人数') {
                                            // 假设其他属性也是行为数据，格式为"XXX人数"
                                            if (key.endsWith('人数')) {
                                                const label = key.replace('人数', '');
                                                timePointResult.detections.push({
                                                    label: label,
                                                    count: item[key]
                                                });
                                            }
                                        }
                                    });
                                }
                            }
                        });
                        
                        processedResult.push(timePointResult);
                    });
                    
                    return { processed_result: processedResult };
                } else {
                    // 旧格式数据，直接返回
                    return data;
                }
            } catch (error) {
                console.error('处理视频数据时出错:', error);
                return { processed_result: [] };
            }
        }
        
        function createStatsPanel(data) {
            const statsPanel = document.createElement('div');
            statsPanel.className = 'stats-panel';
            
            // 提取统计数据
            const stats = extractStatistics(data);
            
            // 计算总帧数
            let totalFrames = 0;
            if (data && data.processed_result && Array.isArray(data.processed_result)) {
                totalFrames = data.processed_result.length;
            }
            
            // 计算总人数的平均值
            let totalPeople = 0;
            if (stats['总人数']) {
                totalPeople = Math.round(stats['总人数'] / totalFrames);
            }
            
            // 添加总人数统计项
            if (stats['总人数'] !== undefined) {
                const statItem = document.createElement('div');
                statItem.className = 'stat-item';
                
                // 创建颜色块
                const colorBlock = document.createElement('div');
                colorBlock.className = 'color-block';
                colorBlock.style.backgroundColor = getBehaviorColor('总人数') || '#00ffff';
                
                // 添加统计文本
                statItem.appendChild(colorBlock);
                statItem.innerHTML += `
                    <strong>总人数:</strong> 
                    <div class="stat-value">${totalPeople}</div>
                    <div class="stat-percentage">人</div>
                `;
                
                statsPanel.appendChild(statItem);
            }
            
            // 添加其他行为统计项
            Object.entries(stats).forEach(([behavior, count]) => {
                if (behavior === '总人数') return; // 跳过总人数，因为已经单独处理
                
                const statItem = document.createElement('div');
                statItem.className = 'stat-item';
                
                // 创建颜色块
                const colorBlock = document.createElement('div');
                colorBlock.className = 'color-block';
                colorBlock.style.backgroundColor = getBehaviorColor(behavior) || '#ffffff';
                
                // 计算百分比
                const percentage = totalPeople > 0 ? Math.round((count / totalFrames / totalPeople) * 100) : 0;
                
                // 计算平均人数
                const avgCount = Math.round(count / totalFrames);
                
                // 添加统计文本
                statItem.appendChild(colorBlock);
                statItem.innerHTML += `
                    <strong>${behavior}:</strong>
                    <div class="stat-value">${percentage}%</div>
                    <div class="stat-percentage">(${avgCount}人)</div>
                `;
                
                statsPanel.appendChild(statItem);
            });
            
            return statsPanel;
        }
        
        function extractStatistics(data) {
            const stats = {};
            
            try {
                // 检查数据类型
                if (!data || !data.processed_result || !Array.isArray(data.processed_result)) {
                    return stats;
                }
                
                // 遍历处理结果
                data.processed_result.forEach(item => {
                    if (item && item.detections) {
                        const detections = Array.isArray(item.detections) ? item.detections : [item.detections];
                        
                        detections.forEach(detection => {
                            if (detection && detection.label) {
                                const label = detection.label;
                                const count = detection.count || 1; // 使用count字段或默认为1
                                
                                if (stats[label] !== undefined) {
                                    stats[label] += count;
                                } else {
                                    stats[label] = count;
                                }
                            }
                        });
                    }
                });
            } catch (error) {
                console.error('提取统计数据时出错:', error);
            }
            
            return stats;
        }
        
        function getBehaviorColor(behavior) {
            // 为不同行为分配颜色
            const colorMap = {
                "抬头": "#FF4081", // 粉色
                "使用手机": "#33FF57", // 绿色
                "站立": "#3357FF", // 蓝色
                "趴桌": "#9C27B0", // 紫色
                "总人数": "#00f0ff" // 青色
            };
            
            return colorMap[behavior] || '#ffffff'; // 返回对应颜色或默认白色
        }
        
        function initTrendChart(data) {
            
            const chartDom = document.getElementById('trend-chart');
            if (!chartDom) return;
            
            const myChart = echarts.init(chartDom);
            
            // 保存图表实例到全局变量
            trendChartInstance = myChart;
            
            // 先设置一个加载中的状态
            myChart.showLoading({
                text: '数据加载中...',
                maskColor: 'rgba(0, 0, 0, 0.3)',
                textColor: '#00ffff'
            });
            
            // 提取时间序列数据
            const timeSeriesData = extractTimeSeriesData(data);
            
            // 添加调试输出
            console.log('折线图原始数据:', data);
            console.log('折线图处理后数据:', timeSeriesData);
            
            // 直接处理时间序列数据
            setTimeout(() => {
                // 检查是否有可用数据
                if (!timeSeriesData || !timeSeriesData.timePoints || Object.keys(timeSeriesData.timePoints).length === 0) {
                    myChart.hideLoading();
                    myChart.setOption({
                        title: {
                            text: '无可用数据',
                            textStyle: {
                                color: '#e0e0ff'
                            },
                            left: 'center',
                            top: 'center'
                        },
                        backgroundColor: 'transparent'
                    });
                    return;
                }
                
                // 准备X轴数据（时间点）
                const timePoints = Object.keys(timeSeriesData.timePoints).map(Number).sort((a, b) => a - b);
                
                // 准备各行为的数据系列
                const seriesData = [];
                
                // 设置颜色和显示顺序
                const colorMap = {
                    "总人数": "#00ffff",
                    "抬头": "#FF4081", // 粉色
                    "使用手机": "#33FF57", // 绿色
                    "站立": "#3357FF", // 蓝色
                    "趴桌": "#9C27B0"  // 紫色
                };
                
                // 显示顺序：总人数优先显示，然后是其他行为
                const behaviorOrder = ["总人数", "抬头", "使用手机", "站立", "趴桌"];
                
                // 按照预定义顺序添加行为
                behaviorOrder.forEach(behavior => {
                    if (timeSeriesData.behaviors[behavior]) {
                        const counts = timeSeriesData.behaviors[behavior];
                        // 检查是否有数据点
                        const hasData = Object.values(counts).some(value => value > 0);
                        if (!hasData && behavior !== "总人数") {
                            return; // 跳过没有数据的行为，总人数除外
                        }
                        
                        const data = timePoints.map(time => counts[time] || 0);
                        
                        seriesData.push({
                            name: behavior,
                            type: 'line',
                            symbol: 'circle',
                            symbolSize: behavior === "总人数" ? 8 : 6,
                            data: data,
                            smooth: true,
                            lineStyle: {
                                width: behavior === "总人数" ? 2 : 2,
                                color: colorMap[behavior] || '#ffffff'
                            },
                            itemStyle: {
                                color: colorMap[behavior] || '#ffffff'
                            },
                            z: behavior === "总人数" ? 5 : 2 // 总人数线条在最上层
                        });
                    }
                });
                
                // 添加一个标记当前时间点的散点图系列（初始隐藏）
                seriesData.push({
                    id: 'highlightSeries',
                    type: 'scatter',
                    symbolSize: 15,
                    symbol: 'circle',
                    itemStyle: {
                        color: 'rgba(255, 255, 255, 0.8)',
                        borderColor: '#fff',
                        borderWidth: 2,
                        shadowBlur: 10,
                        shadowColor: 'rgba(255, 255, 255, 0.8)'
                    },
                    z: 10,
                    data: []
                });
                
                // 图表配置
                const option = {
                    backgroundColor: 'transparent',
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        },
                        formatter: function(params) {
                            // 获取原始秒数
                            const rawSeconds = parseInt(params[0].axisValue.match(/\d+/)[0]);
                            // 转换为时分秒格式
                            const timeString = secondsToTimeString(rawSeconds);
                            
                            let result = `<div style="font-weight:bold;margin-bottom:5px">${timeString}</div>`;
                            
                            // 先找到总人数
                            const totalIndex = params.findIndex(p => p.seriesName === "总人数");
                            if (totalIndex >= 0) {
                                const total = params[totalIndex].value;
                                result += `<div style="color:${colorMap["总人数"]};font-weight:bold;margin-bottom:3px">
                                           总人数: ${total} 人</div>`;
                            }
                            
                            // 添加其他行为
                            params.forEach(param => {
                                if (param.seriesName !== "总人数" && param.seriesName !== undefined) {
                                    result += `<div style="color:${param.color}">
                                              ${param.seriesName}: ${param.value} 人</div>`;
                                }
                            });
                            
                            return result;
                        }
                    },
                    legend: {
                        data: seriesData.filter(item => item.id !== 'highlightSeries').map(item => item.name),
                        textStyle: {
                            color: '#e0e0ff'
                        },
                        top: 10,
                        selected: {
                            // 默认显示所有数据
                            "总人数": true,
                            "抬头": true,
                            "使用手机": true,
                            "站立": true,
                            "趴桌": true
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: timePoints.map(t => {
                                // 将秒数转换为时分秒格式
                                const timeString = secondsToTimeString(Math.floor(t));
                                return timeString;
                            }),
                            axisLine: {
                                lineStyle: {
                                    color: '#5470c6'
                                }
                            },
                            axisLabel: {
                                color: '#e0e0ff',
                                rotate: 45
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            name: '人数',
                            axisLine: {
                                lineStyle: {
                                    color: '#5470c6'
                                }
                            },
                            axisLabel: {
                                color: '#e0e0ff'
                            },
                            splitLine: {
                                lineStyle: {
                                    color: 'rgba(84, 112, 198, 0.2)'
                                }
                            }
                        }
                    ],
                    series: seriesData
                };
                
                // 隐藏加载状态并设置图表
                myChart.hideLoading();
                myChart.setOption(option);
                
                // 添加图例选择变化事件监听器
                myChart.on('legendselectchanged', function() {
                    // 图例状态变化时，如果有当前时间点，则重新计算高亮点
                    if (currentTimePoint !== null) {
                        highlightTimePointInChart(currentTimePoint);
                    }
                });
                
                // 响应窗口大小变化
                window.addEventListener('resize', () => {
                    if (myChart && !myChart.isDisposed()) {
                        myChart.resize();
                    }
                });
                
                // 如果当前已有时间点，更新高亮
                if (currentTimePoint) {
                    highlightTimePointInChart(currentTimePoint);
                }
            }, 1000); // 等待1秒确保数据准备好
        }
        
        function extractTimeSeriesData(data) {
            // 初始化结果对象
            const result = {
                timePoints: {},
                behaviors: {
                    "总人数": {},
                    "站立": {},
                    "使用手机": {},
                    "趴桌": {},
                    "抬头": {}
                }
            };
            
            try {
                // 检查数据格式
                if (!data || !data.processed_result) {
                    return result;
                }
                
                // 直接处理数据，不再尝试获取行为类别
                // 检查是否为数组的数组格式（新API格式）
                if (Array.isArray(data.processed_result) && data.processed_result.length > 0 && Array.isArray(data.processed_result[0])) {
                    // 获取所有时间点
                    const timePointsSet = new Set();
                    data.processed_result.forEach(categoryData => {
                        if (Array.isArray(categoryData)) {
                            categoryData.forEach(item => {
                                if (item && item.时间点 !== undefined) {
                                    timePointsSet.add(item.时间点);
                                }
                            });
                        }
                    });
                    
                    // 为每个时间点添加记录
                    const timePoints = Array.from(timePointsSet).sort((a, b) => a - b);
                    timePoints.forEach(timePoint => {
                        result.timePoints[timePoint] = true;
                    });
                    
                    // 处理总人数数据
                    if (data.processed_result.length >= 1 && Array.isArray(data.processed_result[0])) {
                        data.processed_result[0].forEach(item => {
                            if (item && item.时间点 !== undefined && item.总人数 !== undefined) {
                                result.behaviors["总人数"][item.时间点] = item.总人数;
                            }
                        });
                    }
                    
                    // 处理站立人数数据
                    if (data.processed_result.length >= 2 && Array.isArray(data.processed_result[1])) {
                        data.processed_result[1].forEach(item => {
                            if (item && item.时间点 !== undefined && item.站立人数 !== undefined) {
                                result.behaviors["站立"][item.时间点] = item.站立人数;
                            }
                        });
                    }
                    
                    // 处理使用手机人数数据
                    if (data.processed_result.length >= 3 && Array.isArray(data.processed_result[2])) {
                        data.processed_result[2].forEach(item => {
                            if (item && item.时间点 !== undefined && item.使用手机人数 !== undefined) {
                                result.behaviors["使用手机"][item.时间点] = item.使用手机人数;
                            }
                        });
                    }
                    
                    // 处理趴桌人数数据
                    if (data.processed_result.length >= 4 && Array.isArray(data.processed_result[3])) {
                        data.processed_result[3].forEach(item => {
                            if (item && item.时间点 !== undefined && item.趴桌人数 !== undefined) {
                                result.behaviors["趴桌"][item.时间点] = item.趴桌人数;
                            }
                        });
                    }
                    
                    // 处理抬头人数数据 - 添加处理抬头人数的代码
                    if (data.processed_result.length >= 5 && Array.isArray(data.processed_result[4])) {
                        data.processed_result[4].forEach(item => {
                            if (item && item.时间点 !== undefined && item.抬头人数 !== undefined) {
                                result.behaviors["抬头"][item.时间点] = item.抬头人数;
                            }
                        });
                    } else {
                        // 没有专门的抬头人数数据时，尝试根据总人数和其他行为计算抬头人数
                        timePoints.forEach(timePoint => {
                            const total = result.behaviors["总人数"][timePoint] || 0;
                            const standing = result.behaviors["站立"][timePoint] || 0;
                            const usingPhone = result.behaviors["使用手机"][timePoint] || 0;
                            const headOnDesk = result.behaviors["趴桌"][timePoint] || 0;
                            
                            // 将未被其他行为捕获的学生视为抬头状态
                            // 注意：这是一个近似计算，可能不准确
                            const lookingUp = Math.max(0, total - standing - headOnDesk - usingPhone);
                            result.behaviors["抬头"][timePoint] = lookingUp;
                        });
                    }
                } else {
                    // 处理旧格式数据
                    if (Array.isArray(data.processed_result)) {
                        data.processed_result.forEach((item, index) => {
                            // 记录时间点
                            const frameNumber = item.frame_number || index;
                            result.timePoints[frameNumber] = true;
                            
                            // 处理检测结果
                            if (item.detections) {
                                const detections = Array.isArray(item.detections) ? item.detections : [item.detections];
                                
                                // 统计每个行为在当前时间点的出现次数
                                detections.forEach(detection => {
                                    if (detection && detection.label) {
                                        const label = detection.label;
                                        const count = detection.count || 1;
                                        
                                        if (!result.behaviors[label]) {
                                            result.behaviors[label] = {};
                                        }
                                        
                                        result.behaviors[label][frameNumber] = count;
                                    }
                                });
                            }
                        });
                    }
                }
                
                // 删除空行为
                Object.keys(result.behaviors).forEach(behavior => {
                    if (Object.keys(result.behaviors[behavior]).length === 0) {
                        delete result.behaviors[behavior];
                    }
                });
                
            } catch (error) {
                console.error('提取时间序列数据时出错:', error);
            }
            
            return result;
        }
        
        function initRadarChart(data) {
            const chartDom = document.getElementById('radar-chart');
            if (!chartDom) return;
            
            const myChart = echarts.init(chartDom);
            
            // 提取统计数据
            const stats = extractStatistics(data);
            
            // 计算总数
            const total = Object.values(stats).reduce((sum, count) => sum + count, 0);
            
            // 计算百分比
            const percentages = {};
            Object.entries(stats).forEach(([behavior, count]) => {
                percentages[behavior] = total > 0 ? Math.round((count / total) * 100) : 0;
            });
            
            // 雷达图配置
            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    backgroundColor: 'rgba(0, 20, 40, 0.8)',
                    borderColor: 'rgba(0, 240, 255, 0.5)',
                    borderWidth: 1,
                    textStyle: {
                        color: '#e0e0ff'
                    },
                    formatter: function(params) {
                        return `${params.name}：${params.value}%`;
                    }
                },
                radar: {
                    indicator: Object.keys(percentages).map(behavior => ({
                        name: behavior,
                        max: 100
                    })),
                    shape: 'circle',
                    splitNumber: 5,
                    radius: '65%',
                    center: ['50%', '55%'],
                    axisName: {
                        color: '#00f0ff',
                        fontSize: 12,
                        padding: [3, 15, 3, 15],
                        formatter: function(value) {
                            return value.replace(': ', ':\n');
                        },
                        rich: {
                            a: {
                                color: '#00f0ff',
                                fontSize: 12,
                                lineHeight: 20,
                                fontWeight: 'normal',
                                textShadow: '0 0 5px rgba(0, 240, 255, 0.5)'
                            }
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.2)',
                            width: 1,
                            type: 'dashed'
                        }
                    },
                    splitArea: {
                        show: true,
                        areaStyle: {
                            color: ['rgba(0, 20, 50, 0.1)', 'rgba(0, 30, 60, 0.15)', 'rgba(0, 40, 70, 0.2)', 'rgba(0, 50, 80, 0.25)', 'rgba(0, 60, 90, 0.3)']
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.4)'
                        }
                    }
                },
                series: [
                    {
                        name: '行为占比',
                        type: 'radar',
                        data: [
                            {
                                value: Object.values(percentages),
                                name: '行为占比',
                                areaStyle: {
                                    color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
                                        {
                                            offset: 0,
                                            color: 'rgba(0, 255, 255, 0.7)'
                                        },
                                        {
                                            offset: 1,
                                            color: 'rgba(0, 100, 255, 0.2)'
                                        }
                                    ])
                                },
                                lineStyle: {
                                    color: {
                                        type: 'linear',
                                        x: 0,
                                        y: 0,
                                        x2: 0,
                                        y2: 1,
                                        colorStops: [{
                                            offset: 0, color: '#00ffff'
                                        }, {
                                            offset: 1, color: '#0080ff'
                                        }]
                                    },
                                    width: 2,
                                    shadowColor: 'rgba(0, 240, 255, 0.8)',
                                    shadowBlur: 10
                                },
                                itemStyle: {
                                    color: '#00ffff',
                                    borderColor: '#00ffff',
                                    borderWidth: 2,
                                    shadowColor: 'rgba(0, 240, 255, 0.8)',
                                    shadowBlur: 10
                                },
                                symbol: 'circle',
                                symbolSize: 8
                            }
                        ]
                    }
                ],
                animation: true,
                animationDuration: 1000,
                animationEasing: 'cubicOut',
                animationDelay: function (idx) {
                    return idx * 100;
                }
            };
            
            myChart.setOption(option);
            
            // 响应窗口大小变化
            window.addEventListener('resize', () => {
                if (myChart && !myChart.isDisposed()) {
                    setTimeout(() => {
                        myChart.resize();
                    }, 100);
                }
            });
        }
        
        function generateAIAnalysis(data) {
            const contentElement = document.getElementById('ai-analysis-content');
            
            if (!contentElement) return;
            
            // 显示加载状态
            contentElement.innerHTML = '<div class="ai-loading">小智正在分析课堂状态，请稍候...</div>';
            
            // 提取统计数据用于分析
            const stats = extractStatistics(data);
            
            try {
                // 获取token和domain
                const userToken = localStorage.getItem('token');
                
                // 构造行为统计文本
                let behaviorText = '';
                const total = Object.values(stats).reduce((sum, count) => sum + count, 0);
                
                // 行为类型的中文映射
                const behaviorMap = {
                    "look_up": "抬头",
                    "use_phone": "使用手机",
                    "stand": "站立",
                    "head_on_desk": "趴桌"
                };
                
                // 计算各行为的平均人数和百分比
                Object.entries(stats).forEach(([behavior, count]) => {
                    if (behavior === '总人数') {
                        const avgPeople = Math.round(count / data.processed_result.length);
                        behaviorText += `平均总人数：${avgPeople}人，`;
                    } else {
                        const displayName = behaviorMap[behavior] || behavior;
                        const avgCount = Math.round(count / data.processed_result.length);
                        const percentage = total > 0 ? Math.round((count / total) * 100) : 0;
                        behaviorText += `平均${displayName}率/人数：${percentage}%/${avgCount}人，`;
                    }
                });
                
                // 移除最后的逗号和空格
                behaviorText = behaviorText.replace(/，$/g, '；');
                
                // 调用API获取AI分析结果
                getAiAnalysisResultApi(BACKEND_DOMAIN, userToken, behaviorText)
                    .then(result => {
                        // 更新UI
                        contentElement.innerHTML = typeof result === 'string' ? result : '分析生成失败，请重试';
                    })
                    .catch(error => {
                        console.error('获取AI分析结果时出错:', error);
                        contentElement.innerHTML = '分析生成失败，请重试';
                    });
            } catch (error) {
                console.error('生成AI分析时出错:', error);
                contentElement.innerHTML = '分析生成失败，请重试';
            }
        }

        function loadFirstFrameResult(processedResponse, videoID, userToken) {
            // 尝试识别第一个检测结果
            try {
                if (!processedResponse || !processedResponse.processed_result) return;
                
                // 从已处理的数据中获取第一帧信息
                const firstFrameData = processedResponse.processed_result[0];
                
                if (Array.isArray(firstFrameData) && firstFrameData.length > 0) {
                    // 获取时间点
                    const timePoint = firstFrameData[0]?.时间点;
                    
                    if (timePoint !== undefined) {
                        // 构建检测结果
                        const result = {
                            TF: 'T',
                            frame_number: timePoint,
                            detections: []
                        };
                        
                        // 缓存结果并绘制
                        detectionResultCache[0] = result;
                        if (imageCache[0]) {
                            drawDetectionResults(result);
                        }
                    }
                } else if (firstFrameData && firstFrameData.frame_number !== undefined) {
                    // 处理已转换格式的数据
                    const result = {
                        TF: 'T',
                        frame_number: firstFrameData.frame_number,
                        detections: firstFrameData.detections || []
                    };
                    
                    // 缓存结果并绘制
                    detectionResultCache[0] = result;
                    if (imageCache[0]) {
                        drawDetectionResults(result);
                    }
                }
            } catch (error) {
                console.error('加载第一帧结果时出错:', error);
            }
        }

        // 添加updateBehaviorStats函数
        function updateBehaviorStats(processResult) {
            const statsList = document.getElementById('behavior-stats-list');
            if (!statsList || !processResult) return;

            let stats = {};
            let totalCount = 0;
            
            // 遍历所有行为类型
            Object.entries(processResult).forEach(([behavior, boxes]) => {
                if (Array.isArray(boxes)) {
                    if (behavior === 'yolo_model_output') {
                        totalCount = boxes.length;
                    } else {
                        stats[behavior] = boxes.length;
                    }
                }
            });

            // 行为类型的中文映射
            const behaviorMap = {
                "look_up": "抬头",
                "use_phone": "使用手机",
                "stand": "站立",
                "head_on_desk": "趴桌"
            };

            // 清空现有内容
            statsList.innerHTML = '';
            
            // 创建总人数显示元素
            const totalElement = document.createElement('div');
            totalElement.className = 'stat-item';
            totalElement.style.display = 'flex';
            totalElement.style.justifyContent = 'space-between';
            totalElement.style.alignItems = 'center';
            totalElement.style.width = '100%';
            totalElement.style.marginBottom = '10px';
            totalElement.style.maxWidth = '180px'; // 添加最大宽度限制
            
            // 添加总人数信息
            const totalLeftDiv = document.createElement('div');
            totalLeftDiv.style.display = 'flex';
            totalLeftDiv.style.alignItems = 'center';
            totalLeftDiv.style.maxWidth = '80px'; // 限制左侧区域宽度
            
            const totalLabel = document.createElement('strong');
            totalLabel.textContent = '总人数:';
            totalLabel.style.fontSize = '0.9rem'; // 适当减小字体大小
            
            totalLeftDiv.appendChild(totalLabel);
            
            const totalRightDiv = document.createElement('div');
            totalRightDiv.style.display = 'flex';
            totalRightDiv.style.alignItems = 'center';
            totalRightDiv.style.justifyContent = 'flex-end'; // 右对齐
            totalRightDiv.style.maxWidth = '80px'; // 限制右侧区域宽度
            
            const totalValue = document.createElement('div');
            totalValue.className = 'stat-value';
            totalValue.textContent = totalCount;
            
            const totalUnit = document.createElement('div');
            totalUnit.className = 'stat-percentage';
            totalUnit.style.marginLeft = '5px';
            totalUnit.textContent = '人';
            
            totalRightDiv.appendChild(totalValue);
            totalRightDiv.appendChild(totalUnit);
            
            totalElement.appendChild(totalLeftDiv);
            totalElement.appendChild(totalRightDiv);
            
            // 添加总人数元素到统计列表
            statsList.appendChild(totalElement);
            
            // 添加每种行为的统计信息，每个行为单独一行
            Object.entries(stats).forEach(([behavior, count]) => {
                const displayName = behaviorMap[behavior] || behavior;
                // 计算百分比
                const percentage = totalCount > 0 ? Math.round((count / totalCount) * 100) : 0;
                
                // 根据行为类型定义不同的边框颜色
                let borderColor = '#00f0ff'; // 默认颜色
                let backgroundColor = '#00f0ff';
                if (behavior === 'stand') {
                    borderColor = '#3357FF'; // 站立-蓝色
                    backgroundColor = '#3357FF';
                } else if (behavior === 'use_phone') {
                    borderColor = '#33FF57'; // 使用手机-绿色
                    backgroundColor = '#33FF57';
                } else if (behavior === 'head_on_desk') {
                    borderColor = '#9C27B0'; // 趴桌-紫色
                    backgroundColor = '#9C27B0';
                } else if (behavior === 'look_up') {
                    borderColor = '#FF4081'; // 抬头-粉色
                    backgroundColor = '#FF4081';
                }
                
                // 创建行为统计项
                const behaviorItem = document.createElement('div');
                behaviorItem.className = 'stat-item';
                behaviorItem.style.borderLeftColor = borderColor;
                behaviorItem.style.width = '100%';
                behaviorItem.style.maxWidth = '180px'; // 添加最大宽度限制
                behaviorItem.style.marginBottom = '10px';
                behaviorItem.style.display = 'flex';
                behaviorItem.style.justifyContent = 'space-between';
                behaviorItem.style.alignItems = 'center';
                
                // 创建左侧标签
                const leftDiv = document.createElement('div');
                leftDiv.style.display = 'flex';
                leftDiv.style.alignItems = 'center';
                leftDiv.style.maxWidth = '80px'; // 限制左侧区域宽度
                
                const label = document.createElement('strong');
                label.textContent = displayName + ':';
                label.style.fontSize = '0.9rem'; // 适当减小字体大小
                
                leftDiv.appendChild(label);
                
                // 创建右侧值
                const rightDiv = document.createElement('div');
                rightDiv.style.display = 'flex';
                rightDiv.style.alignItems = 'center';
                rightDiv.style.justifyContent = 'flex-end'; // 右对齐
                rightDiv.style.maxWidth = '80px'; // 限制右侧区域宽度
                
                const value = document.createElement('div');
                value.className = 'stat-value';
                value.style.marginRight = '5px';
                value.textContent = count;
                
                const unit = document.createElement('div');
                unit.className = 'stat-percentage';
                unit.style.marginRight = '5px';
                unit.textContent = '人';
                
                const percentageElem = document.createElement('div');
                percentageElem.className = 'stat-percentage';
                percentageElem.textContent = percentage + '%';
                
                rightDiv.appendChild(value);
                rightDiv.appendChild(unit);
                rightDiv.appendChild(percentageElem);
                
                // 组装行为统计项
                behaviorItem.appendChild(leftDiv);
                behaviorItem.appendChild(rightDiv);
                
                // 直接添加到统计列表
                statsList.appendChild(behaviorItem);
            });

            // 更新饼图
            updatePieChart({...stats, total: totalCount});
        }

        function updatePieChart(stats) {
            const chartDom = document.getElementById('current-frame-pie-chart');
            if (!chartDom || !window.echarts) return;

            const myChart = echarts.init(chartDom);
            
            // 行为类型的中文映射
            const behaviorMap = {
                "look_up": "抬头",
                "use_phone": "使用手机",
                "stand": "站立",
                "head_on_desk": "趴桌"
            };

            // 获取总人数
            const totalCount = stats.total || 0;

            // 准备饼图数据
            const data = Object.entries(stats)
                .filter(([key]) => key !== 'total') // 排除总数
                .map(([behavior, count]) => {
                    // 计算百分比
                    const percentage = totalCount > 0 ? Math.round((count / totalCount) * 100) : 0;
                    return {
                        value: count,
                        name: behaviorMap[behavior] || behavior,
                        percentage: percentage
                    };
                });

            // 饼图配置
            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}: {d}% ({c}人)',
                    backgroundColor: 'rgba(20, 20, 40, 0.9)',
                    borderColor: 'rgba(0, 240, 255, 0.3)',
                    textStyle: {
                        color: '#e0e0ff'
                    }
                },
                series: [
                    {
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: true,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#0a0a1a',
                            borderWidth: 2
                        },
                        label: {
                            show: true,
                            position: 'outside',
                            formatter: '{b}: {d}%',
                            color: '#e0e0ff',
                            textShadow: '0 0 5px rgba(0, 240, 255, 0.5)',
                            fontSize: 12,
                            distance: 20,
                            alignTo: 'labelLine',
                            bleedMargin: 5
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: 14,
                                fontWeight: 'bold'
                            },
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 240, 255, 0.5)'
                            }
                        },
                        labelLine: {
                            show: true,
                            length: 20,
                            length2: 30,
                            smooth: true,
                            lineStyle: {
                                color: 'rgba(0, 240, 255, 0.3)',
                                width: 1
                            }
                        },
                        data: data.map(item => ({
                            ...item,
                            itemStyle: {
                                color: getBehaviorColor(item.name)
                            }
                        }))
                    }
                ]
            };

            // 设置图表选项
            myChart.setOption(option);

            // 响应窗口大小变化
            window.addEventListener('resize', () => {
                myChart.resize();
            });
        }

        function getBehaviorColor(behavior) {
            // 为不同行为分配颜色
            const colorMap = {
                "抬头": "#FF4081", // 粉色
                "使用手机": "#33FF57", // 绿色
                "站立": "#3357FF", // 蓝色
                "趴桌": "#9C27B0", // 紫色
                "总人数": "#00f0ff" // 青色
            };
            
            return colorMap[behavior] || '#ffffff'; // 返回对应颜色或默认白色
        }

        // 增强绘制检测框函数
        const originalDrawDetectionBoxes = drawDetectionBoxes;
        drawDetectionBoxes = function(processResult, selectedBehavior) {
            // 调用原始函数
            originalDrawDetectionBoxes(processResult, selectedBehavior);
        };
        
        // 创建UI元素
        document.addEventListener('DOMContentLoaded', function() {
            // 添加返回按钮点击事件
            document.getElementById('back-button').addEventListener('click', () => {
                window.location.href = FRONT_END_DOMAIN + '/video_processing_result_page';
            });
        });

        // 添加函数：更新图片上方的行为人数统计
        function updateBehaviorCountSummary(processResult) {
            if (!processResult) return;
            
            // 获取或创建行为统计摘要元素
            let summaryElement = document.getElementById('behavior-count-summary');
            if (!summaryElement) {
                summaryElement = document.createElement('div');
                summaryElement.id = 'behavior-count-summary';
                summaryElement.className = 'behavior-count-summary';
                document.querySelector('.preview-center').appendChild(summaryElement);
            }
            
            // 统计各种行为的人数
            let stats = {};
            let totalCount = 0;
            
            // 遍历所有行为类型统计数量
            Object.entries(processResult).forEach(([behavior, boxes]) => {
                if (Array.isArray(boxes)) {
                    if (behavior === 'yolo_model_output') {
                        totalCount = boxes.length;
                    } else {
                        stats[behavior] = boxes.length;
                    }
                }
            });
            
            // 行为类型的中文映射
            const behaviorMap = {
                "look_up": "抬头",
                "use_phone": "使用手机",
                "stand": "站立",
                "head_on_desk": "趴桌"
            };
            
            // 创建显示文本
            let summaryText = `总人数: ${totalCount} `;
            
            // 添加各行为人数
            Object.entries(stats).forEach(([behavior, count]) => {
                const displayLabel = behaviorMap[behavior] || behavior;
                summaryText += `| ${displayLabel}: ${count} `;
            });
            
            // 更新元素内容
            summaryElement.textContent = summaryText;
            summaryElement.style.display = 'block';
        }

        // 更新当前帧的饼图和柱状图
        function updateCharts(processResult) {
            if (!processResult) {
                console.warn('未提供有效的处理结果数据，尝试从缓存获取');
                // 尝试从缓存读取
                if (imageProcessResults[currentImageIndex]) {
                    processResult = imageProcessResults[currentImageIndex];
                } else {
                    console.error('无法获取当前帧的图表数据');
                    return;
                }
            }
            
            // 检查ECharts是否加载
            if (!window.echarts) {
                // console.log('ECharts尚未加载，等待加载完成后更新图表');
                // 添加事件监听，等待ECharts加载完成
                document.addEventListener('echartsLoaded', function echartsLoadedHandler() {
                    // 移除事件监听，避免多次执行
                    document.removeEventListener('echartsLoaded', echartsLoadedHandler);
                    // console.log('ECharts加载事件触发，现在更新图表');
                    setTimeout(() => updateCharts(processResult), 100);
                });
                
                // 如果长时间未加载成功，尝试手动重新加载ECharts
                setTimeout(() => {
                    if (!window.echarts) {
                        console.warn('ECharts长时间未加载，尝试重新加载');
                        loadECharts()
                            .then(() => {
                                // console.log('手动加载ECharts成功，更新图表');
                                updateCharts(processResult);
                            })
                            .catch(err => {
                                console.error('手动加载ECharts失败:', err);
                            });
                    }
                }, 3000);
                
                return;
            }
            
            // 统计各种行为的人数
            let stats = {};
            let totalCount = 0;
            
            // 初始化所有行为计数为0，确保所有图表都有完整数据
            stats = {
                "look_up": 0,
                "use_phone": 0,
                "stand": 0,
                "head_on_desk": 0
            };
            
            // 遍历所有行为类型统计数量
            Object.entries(processResult).forEach(([behavior, boxes]) => {
                if (Array.isArray(boxes)) {
                    if (behavior === 'yolo_model_output') {
                        totalCount = boxes.length;
                    } else {
                        stats[behavior] = boxes.length;
                    }
                }
            });
            
            // 如果没有YOLO检测结果，计算一个总数
            if (totalCount === 0) {
                totalCount = Object.values(stats).reduce((sum, count) => sum + count, 0);
            }
            
            // 更新饼图
            // updatePieChart({...stats, total: totalCount});
            
            // 更新柱状图
            // updateBarChart({...stats, total: totalCount});
            
            // 更新分析结果面板的水平柱状图
            updateAnalysisSummary();
            
            // 确保其他相关图表也被更新（但不包括异常行为柱状图，它由专门的函数更新一次）
            try {
                // 检查是否已经更新过异常行为柱状图，避免重复调用导致柱状图抖动
                if (!window._abnormalChartUpdated && document.getElementById('abnormal-behavior-chart')) {
                    // 更新异常行为柱状图
                    updateAbnormalBehaviorChart(
                        stats.use_phone || 0,
                        stats.stand || 0,
                        stats.head_on_desk || 0,
                        stats.look_up || 0
                    );
                    window._abnormalChartUpdated = true;
                    
                    // 延迟重置标志
                    setTimeout(() => {
                        window._abnormalChartUpdated = false;
                    }, 500);
                }
                
                // 更新雷达图
                updateFrameInfoRadarChart();
                
                // 更新行为饼图
                updateBehaviorPieChart();
            } catch (e) {
                console.error('更新附加图表时出错:', e);
            }
        }
        
        function updateBarChart(stats) {
            const chartDom = document.getElementById('current-frame-bar-chart');
            if (!chartDom || !window.echarts) return;
            
            // 初始化图表
            let myChart = echarts.getInstanceByDom(chartDom);
            if (!myChart) {
                myChart = echarts.init(chartDom);
            }
            
            // 行为类型的中文映射
            const behaviorMap = {
                "look_up": "抬头",
                "use_phone": "使用手机",
                "stand": "站立",
                "head_on_desk": "趴桌"
            };
            
            // 准备柱状图数据
            const data = Object.entries(stats)
                .filter(([key]) => key !== 'total' && key !== 'yolo_model_output') // 排除总数和yolo输出
                .map(([behavior, count]) => {
                    return {
                        value: count || 0, // 确保count为0时也能正常显示
                        name: behaviorMap[behavior] || behavior
                    };
                });
            
            // 确保至少有默认数据，防止空图表
            if (data.length === 0) {
                Object.entries(behaviorMap).forEach(([behavior, name]) => {
                    data.push({
                        value: 0,
                        name: name
                    });
                });
            }
            
            // 柱状图配置
            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: '{b}: {c}人',
                    backgroundColor: 'rgba(20, 20, 40, 0.9)',
                    borderColor: 'rgba(0, 240, 255, 0.3)',
                    textStyle: {
                        color: '#e0e0ff'
                    }
                },
                grid: {
                    left: '5%',
                    right: '5%',
                    bottom: '10%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: data.map(item => item.name),
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.3)'
                        }
                    },
                    axisLabel: {
                        color: '#e0e0ff',
                        fontSize: 12,
                        interval: 0, // 强制显示所有标签
                        rotate: data.length > 5 ? 30 : 0 // 如果标签太多就旋转
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '人数',
                    nameTextStyle: {
                        color: '#00f0ff'
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.3)'
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.1)'
                        }
                    },
                    axisLabel: {
                        color: '#e0e0ff',
                        fontSize: 12
                    },
                    minInterval: 1, // 强制y轴以整数显示
                    max: stats.total || 10 // 设置最大值为总人数，如果总人数为0则使用10作为默认值
                },
                series: [
                    {
                        type: 'bar',
                        data: data.map(item => ({
                            value: item.value,
                            itemStyle: {
                                color: getBehaviorColor(item.name),
                                borderRadius: [5, 5, 0, 0]
                            }
                        })),
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(255, 255, 255, 0.05)',
                            borderRadius: [5, 5, 0, 0]
                        },
                        barWidth: '50%',
                        label: {
                            show: true,
                            position: 'top',
                            color: '#e0e0ff',
                            fontSize: 12,
                            formatter: '{c}'
                        },
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 15,
                                shadowColor: 'rgba(0, 240, 255, 0.5)'
                            }
                        }
                    }
                ],
                animationDuration: 1000,
                animationEasing: 'cubicOut'
            };
            
            // 设置图表选项
            myChart.setOption(option);
            
            // 响应窗口大小变化
            window.addEventListener('resize', () => {
                if (myChart && !myChart.isDisposed()) {
                    myChart.resize();
                }
            });
        }

        // 添加自动播放功能
        function toggleAutoPlay() {
            // 这个函数只在用户点击按钮时被调用
            if (isAutoPlaying) {
                stopAutoPlay();
            } else {
                startAutoPlay();
            }
            updatePlayButton();
        }
        
        function startAutoPlay() {
            isAutoPlaying = true;
            if (autoPlayInterval) {
                clearInterval(autoPlayInterval);
            }
            autoPlayInterval = setInterval(() => {
                const nextIndex = currentImageIndex + 1 < currentImagePaths.length ? currentImageIndex + 1 : 0;
                // 检查下一张图片是否已加载并分析完成
                if (imageCache[nextIndex] && imageProcessResults[nextIndex]) {
                    // 导航到下一帧 - 这已经会触发updateAllUIComponents()来更新所有UI和图表
                    navigateFrames(1);
                } else {
                    // 如果下一张图片未加载完成，暂停定时器并开始加载
                    clearInterval(autoPlayInterval);
                    autoPlayInterval = null;
                    
                    // 优先加载下一张图片
                    if (!imageCache[nextIndex]) {
                        showLoadingNotification('正在等待下一帧加载完成...', 1000);
                        loadSingleImageWithRetry(nextIndex, 3)
                            .then(() => {
                                // 加载完成后重新启动自动播放
                                if (isAutoPlaying) {
                                    startAutoPlay();
                                }
                            });
                    } else if (!imageProcessResults[nextIndex]) {
                        // 图片已加载但分析结果未完成
                        showLoadingNotification('正在等待下一帧分析完成...', 1000);
                        // 等待图片分析结果完成后再继续
                        const checkInterval = setInterval(() => {
                            if (imageProcessResults[nextIndex]) {
                                clearInterval(checkInterval);
                                // 分析完成后重新启动自动播放
                                if (isAutoPlaying) {
                                    startAutoPlay();
                                }
                            }
                        }, 300);
                    }
                }
            }, autoPlaySpeed);
            updatePlayButton();
        }
        
        function stopAutoPlay() {
            isAutoPlaying = false;
            if (autoPlayInterval) {
                clearInterval(autoPlayInterval);
                autoPlayInterval = null;
            }
            updatePlayButton();
        }
        
        function updatePlayButton() {
            const playButton = document.getElementById('auto-play-button');
            const controlsContainer = document.querySelector('.playback-controls');
            const statusText = document.querySelector('.control-status');
            
            if (playButton) {
                if (isAutoPlaying) {
                    playButton.innerHTML = '<svg viewBox="0 0 24 24"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"></path></svg>';
                    playButton.title = '暂停';
                    playButton.classList.remove('paused');
                    if (controlsContainer) controlsContainer.classList.remove('paused');
                    if (statusText) statusText.textContent = '正在播放';
                } else {
                    playButton.innerHTML = '<svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg>';
                    playButton.title = '播放';
                    playButton.classList.add('paused');
                    if (controlsContainer) controlsContainer.classList.add('paused');
                    if (statusText) statusText.textContent = '已暂停';
                }
            }
        }
        
        function changePlaySpeed(speed) {
            autoPlaySpeed = 2000;
            if (isAutoPlaying) {
                stopAutoPlay();
                startAutoPlay();
            }
            // 更新速度显示
            const speedDisplay = document.getElementById('play-speed-display');
            if (speedDisplay) {
                speedDisplay.textContent = '';
            }
        }

        // 移除下滑自动暂停的功能，只保留恢复播放的部分
        window.addEventListener('scroll', () => {
            const videoPreviewContainer = document.getElementById('video-preview-container');
            if (!videoPreviewContainer) return;
            
            const containerRect = videoPreviewContainer.getBoundingClientRect();
            const isVisible = (
                containerRect.top < window.innerHeight &&
                containerRect.bottom > 0
            );
            
            // 移除了下滑自动暂停的代码
            // 只保留恢复播放的部分
            if (isVisible && !isAutoPlaying && document.visibilityState === 'visible') {
                // 如果视频容器在可视区域内，并且页面可见，恢复播放
                // 但仅当之前因滚动而暂停时才自动恢复
                if (window.autoPlayWasPaused) {
                    startAutoPlay();
                    window.autoPlayWasPaused = false;
                }
            }
        });

        // 添加页面可见性变化检测
        document.addEventListener('visibilitychange', () => {
            if (document.visibilityState === 'hidden' && isAutoPlaying) {
                // 当页面不可见时暂停播放并记录状态
                window.autoPlayWasPaused = true;
                stopAutoPlay();
            } else if (document.visibilityState === 'visible' && window.autoPlayWasPaused) {
                // 当页面再次可见且之前因不可见而暂停时，恢复播放
                startAutoPlay();
                window.autoPlayWasPaused = false;
            }
        });

        // 在窗口大小改变时，判断是否需要调整自动播放状态
        window.addEventListener('resize', function() {
            // 利用已有的窗口调整大小处理逻辑，添加自动播放检查
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                const videoPreviewContainer = document.getElementById('video-preview-container');
                if (videoPreviewContainer) {
                    const containerRect = videoPreviewContainer.getBoundingClientRect();
                    const isVisible = (
                        containerRect.top < window.innerHeight &&
                        containerRect.bottom > 0
                    );
                    
                    // 移除窗口大小调整时的自动暂停逻辑
                    // 只保留恢复播放的部分
                    if (isVisible && window.autoPlayWasPaused) {
                        startAutoPlay();
                        window.autoPlayWasPaused = false;
                    }
                }
                
                // 执行原有的调整大小逻辑
                const activeButton = document.querySelector('.behavior-button.active');
                const selectedBehavior = activeButton ? activeButton.dataset.behavior : 'all';
                
                const currentImage = document.getElementById('current-image');
                if (currentImage && currentImage.complete && detectionResultCache[currentImageIndex]) {
                    drawDetectionBoxes(detectionResultCache[currentImageIndex], selectedBehavior);
                }
            }, 200);
        });

        // 新增函数: 更新分析结果面板
        function updateAnalysisSummary() {
            const summaryEl = document.getElementById('frame-analysis-summary');
            if (!summaryEl) return;
            
            // 获取当前帧的图像处理结果
            const frameResult = imageProcessResults[currentImageIndex] || {};
            
            // 统计各行为出现的人数
            const behaviorsDetected = [];
            
            Object.entries(frameResult).forEach(([key, value]) => {
                // 跳过YOLO模型输出
                if (key === 'yolo_model_output') return;
                
                // 确保是数组并计算数量
                if (Array.isArray(value)) {
                    const count = value.length;
                    if (count > 0) {
                        // 将英文行为名称转换为中文
                        let behaviorName = key;
                        switch (key) {
                            case 'look_up':
                                behaviorName = '抬头';
                                break;
                            case 'use_phone':
                                behaviorName = '使用手机';
                                break;
                            case 'stand':
                                behaviorName = '站立';
                                break;
                            case 'head_on_desk':
                                behaviorName = '趴桌';
                                break;
                        }
                        
                        behaviorsDetected.push({
                            name: behaviorName,
                            count: count
                        });
                    }
                }
            });
            
            // 创建分析文本
            let analysisHtml = '';
            if (behaviorsDetected.length > 0) {
                // 使用文本形式显示行为统计
                analysisHtml = '<div style="margin-top: 10px;">';
                behaviorsDetected.forEach(item => {
                    analysisHtml += `<p>${item.name}: ${item.count}人</p>`;
                });
                analysisHtml += '</div>';
                
                summaryEl.innerHTML = analysisHtml;
            } else {
                analysisHtml = '<p>当前帧未检测到任何行为。</p>';
                summaryEl.innerHTML = analysisHtml;
            }
        }
        
        // 新增函数: 更新帧信息雷达图
        function updateFrameInfoRadarChart() {
            const waffleChartDom = document.getElementById('frame-info-radar-chart');
            if (!waffleChartDom || !window.echarts) return;

            // 确保容器可见
            waffleChartDom.style.visibility = 'visible';
            
            // 创建图表实例前，确保容器尺寸正确
            const containerWidth = waffleChartDom.clientWidth;
            const containerHeight = waffleChartDom.clientHeight;
            
            if (containerWidth === 0 || containerHeight === 0) {
                console.warn('雷达图容器尺寸为零，延迟初始化');
                setTimeout(updateFrameInfoRadarChart, 200);
                return;
            }

            // 获取或创建echarts实例
            let myChart = echarts.getInstanceByDom(waffleChartDom);
            if (!myChart) {
                myChart = echarts.init(waffleChartDom);
            } else {
                myChart.clear(); // 清除旧图表
            }
            
            let totalPersonCount = 0;
            let behaviorCounts = {};

            // 从当前帧获取检测结果
            if (imageProcessResults[currentImageIndex]) {
                const results = imageProcessResults[currentImageIndex];
                
                // 获取总人数
                if (results.yolo_model_output && Array.isArray(results.yolo_model_output)) {
                    totalPersonCount = results.yolo_model_output.length;
                }

                // 统计各种行为的人数
                Object.entries(results).forEach(([behavior, boxes]) => {
                    if (behavior !== 'yolo_model_output' && Array.isArray(boxes)) {
                        behaviorCounts[behavior] = boxes.length;
                    }
                });

                // 如果没有YOLO输出，则总人数为所有行为人数之和
                if (totalPersonCount === 0) {
                    totalPersonCount = Object.values(behaviorCounts).reduce((sum, count) => sum + count, 0);
                }

                // console.log("华夫饼图数据:", {
                //     totalPersonCount,
                //     behaviorCounts
                // });
            }

            // 将行为数据转换为华夫饼图数据
            const behaviorData = [];
            const behaviorColors = {
                'look_up': '#FF4081',       // 粉色
                'use_phone': '#33FF57',     // 绿色
                'stand': '#3357FF',         // 蓝色
                'head_on_desk': '#9C27B0'   // 紫色
            };
            
            const behaviorNames = {
                'look_up': '抬头',
                'use_phone': '玩手机',
                'stand': '站立',
                'head_on_desk': '趴桌'
            };
            
            // 只添加行为数据，不包括总人数
            Object.entries(behaviorCounts).forEach(([behavior, count]) => {
                if (count > 0) { // 只添加有数据的行为
                    behaviorData.push({
                        value: count,
                        name: behaviorNames[behavior] || behavior,
                        itemStyle: {
                            color: behaviorColors[behavior] || '#00f0ff'
                        }
                    });
                }
            });
            
            // 如果没有数据，添加一个占位条目
            if (behaviorData.length === 0) {
                behaviorData.push({
                    value: 1,
                    name: '无异常行为',
                    itemStyle: {
                        color: '#00f0ff'
                    }
                });
            }
            
            // 根据容器大小调整饼图配置
            let fontSize = 14;
            let radius = '65%';
            let center = ['50%', '55%'];
            
            // 根据容器宽度调整
            if (containerWidth < 200) {
                fontSize = 12;
                radius = '60%';
            }
            
            // 创建华夫饼图
            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}: {c}人',
                    backgroundColor: 'rgba(20, 20, 40, 0.9)',
                    borderColor: 'rgba(0, 240, 255, 0.3)',
                    textStyle: {
                        color: '#e0e0ff'
                    }
                },
                title: {
                    text: '课堂行为分布',
                    textStyle: {
                        color: '#00f0ff',
                        fontSize: fontSize,
                        fontWeight: 'normal'
                    },
                    left: 'center',
                    top: 0
                },
                series: [{
                    type: 'pie',
                    radius: radius,
                    center: center,
                    itemStyle: {
                        borderColor: 'rgba(0, 0, 20, 0.5)',
                        borderWidth: 1,
                        borderRadius: 4,
                        shadowBlur: 10,
                        shadowColor: 'rgba(0, 240, 255, 0.3)',
                    },
                    label: {
                        show: true,
                        formatter: '{b}: {c}人',
                        color: '#7adbff',
                        fontSize: fontSize - 2, // 标签字体稍小
                        fontWeight: 'normal',
                        position: 'outside',
                        distanceToLabelLine: 5
                    },
                    labelLine: {
                        show: true,
                        length: 10,
                        length2: 5,
                        lineStyle: {
                            color: 'rgba(122, 219, 255, 0.6)'
                        }
                    },
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 20,
                            shadowColor: 'rgba(0, 240, 255, 0.7)'
                        },
                        label: {
                            color: '#00f0ff',
                            fontWeight: 'bold'
                        }
                    },
                    animationType: 'scale',
                    animationEasing: 'elasticOut',
                    data: behaviorData
                }]
            };

            // 设置选项
            myChart.setOption(option);

            // 响应窗口大小变化
            window.addEventListener('resize', () => {
                if (myChart && !myChart.isDisposed()) {
                    setTimeout(() => {
                        myChart.resize();
                    }, 100);
                }
            });
            
            // 立即执行一次resize以确保正确渲染
            setTimeout(() => {
                if (myChart && !myChart.isDisposed()) {
                    myChart.resize();
                }
            }, 200);
        }

        // 添加新的函数：更新行为饼图
        function updateBehaviorPieChart() {
            const pieChartDom = document.getElementById('behavior-pie-chart');
            if (!pieChartDom || !window.echarts) return;
            
            // 获取当前帧的所有行为检测数据
            let behaviorsDetected = [];
            let totalDetections = 0;
            
            if (imageProcessResults[currentImageIndex]) {
                const results = imageProcessResults[currentImageIndex];
                const behaviorNames = {
                    "use_phone": "使用手机",
                    "stand": "站立",
                    "head_on_desk": "趴桌",
                    "look_up": "抬头"
                };
                
                // 收集所有检测到的行为
                Object.entries(results).forEach(([behavior, boxes]) => {
                    if (behavior !== 'yolo_model_output' && Array.isArray(boxes) && boxes.length > 0) {
                        behaviorsDetected.push({
                            name: behaviorNames[behavior] || behavior,
                            count: boxes.length
                        });
                        totalDetections += boxes.length;
                    }
                });
            }
            
            // 准备数据
            const data = behaviorsDetected.map(item => ({
                value: item.count,
                name: item.name
            }));
            
            // 初始化图表
            let radarChart = echarts.getInstanceByDom(pieChartDom);
            if (!radarChart) {
                radarChart = echarts.init(pieChartDom);
            }
            
            // 获取雷达图的指标名称和数据
            const indicator = [];
            let seriesData = [];
            
            // 从检测结果动态生成类别，而不是使用固定的数组
            let behaviorValues = {};
            
            // 如果有检测到行为，使用它们作为类别
            if (data.length > 0) {
                // 提取所有行为名称并创建值对象
                data.forEach(item => {
                    behaviorValues[item.name] = item.value;
                });
            } else {
                // 如果没有检测到任何行为，使用默认类别集
                const defaultBehaviors = ['使用手机', '站立', '趴桌', '抬头'];
                defaultBehaviors.forEach(behavior => {
                    behaviorValues[behavior] = 0;
                });
            }
            
            // 计算最大值用于指标上限
            let maxCount = 10; // 默认最大值
            
            if (data.length > 0) {
                // 更新最大值
                maxCount = Math.max(...data.map(item => item.value), 5); // 至少为5
            }
            
            // 构建雷达图指标
            Object.keys(behaviorValues).forEach(behavior => {
                indicator.push({ name: behavior, max: maxCount });
            });
            
            // 构建雷达图数据（二维数组格式）
            const values = Object.values(behaviorValues);
            seriesData = [values]; // 注意：这里需要是二维数组
            
            // 雷达图配置
            const radarOption = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        if (params.componentSubType === 'radar') {
                            // 获取当前点击的维度索引
                            const index = params.dimensionIndex !== undefined ? params.dimensionIndex : params.encode.tooltip[0];
                            // 获取指标名称和数值
                            const name = indicator[index] ? indicator[index].name : '';
                            const value = params.value[index];
                            return `${name}: ${value}人`;
                        }
                        return params.name;
                    },
                    backgroundColor: 'rgba(0, 10, 30, 0.85)',
                    borderColor: 'rgba(0, 240, 255, 0.5)',
                    borderWidth: 1,
                    textStyle: {
                        color: '#e0e0ff'
                    },
                    shadowColor: 'rgba(0, 240, 255, 0.3)',
                    shadowBlur: 15
                },
                radar: {
                    indicator: indicator,
                    shape: 'polygon',
                    splitNumber: 4,
                    radius: '65%',
                    center: ['50%', '55%'],
                    name: {
                        textStyle: {
                            color: '#00f0ff',
                            fontSize: 11,
                            fontWeight: 'normal',
                            padding: [3, 5],
                            textShadow: '0 0 5px rgba(0, 240, 255, 0.7)'
                        },
                        formatter: function(value) {
                            if (value.length > 4) {
                                return value.substring(0, 4) + '\n' + value.substring(4);
                            }
                            return value;
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.3)',
                            width: 1.5,
                            type: 'solid'
                        }
                    },
                    splitArea: {
                        show: true,
                        areaStyle: {
                            color: ['rgba(0, 20, 60, 0.1)', 'rgba(0, 30, 70, 0.15)', 'rgba(0, 40, 80, 0.2)', 'rgba(0, 50, 90, 0.25)']
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.5)',
                            width: 1.5
                        }
                    }
                },
                series: [{
                    type: 'radar',
                    data: [{
                        value: seriesData[0],
                        name: '行为分布',
                        symbol: 'diamond',
                        symbolSize: 7,
                        lineStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 1,
                                y2: 0,
                                colorStops: [{
                                    offset: 0, color: '#00ffff'
                                }, {
                                    offset: 1, color: '#0080ff'
                                }]
                            },
                            width: 2,
                            shadowColor: 'rgba(0, 240, 255, 0.7)',
                            shadowBlur: 8
                        },
                        areaStyle: {
                            color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
                                {
                                    offset: 0,
                                    color: 'rgba(0, 255, 255, 0.6)'
                                },
                                {
                                    offset: 1,
                                    color: 'rgba(0, 60, 120, 0.2)'
                                }
                            ]),
                            shadowColor: 'rgba(0, 240, 255, 0.5)',
                            shadowBlur: 10
                        },
                        itemStyle: {
                            color: '#00f0ff',
                            borderColor: '#ffffff',
                            borderWidth: 1,
                            shadowColor: 'rgba(0, 240, 255, 1)',
                            shadowBlur: 10
                        }
                    }]
                }],
                animationDuration: 1200,
                animationEasing: 'elasticOut',
                animationDelay: function (idx) {
                    return idx * 100;
                }
            };
            
            // 设置雷达图选项
            radarChart.setOption(radarOption);
            
            // 设置响应式
            window.addEventListener('resize', () => {
                setTimeout(() => {
                    radarChart.resize();
                }, 100);
            });
        }

        // 添加用于显示行为平均占比的饼图
        function createAverageBehaviorPieChart() {
            // 创建饼图容器
            const container = document.createElement('div');
            container.className = 'average-behavior-pie-container';
            container.innerHTML = `
                <h2>行为平均占比分析</h2>
                <div class="chart-tip">展示整个视频中各类行为的平均占比</div>
                <div class="pie-chart" id="average-behavior-pie-chart"></div>
            `;
            
            // 检查是否已存在底部分析容器
            let bottomAnalysisContainer = document.getElementById('bottom-analysis-container');
            if (!bottomAnalysisContainer) {
                // 创建底部分析容器
                bottomAnalysisContainer = document.createElement('div');
                bottomAnalysisContainer.id = 'bottom-analysis-container';
                bottomAnalysisContainer.className = 'bottom-analysis-container';
                document.body.appendChild(bottomAnalysisContainer);
            }
            
            // 创建右侧饼图容器
            const rightContainer = document.createElement('div');
            rightContainer.className = 'analysis-chart-container';
            rightContainer.appendChild(container);
            
            // 将饼图容器添加到底部分析容器
            bottomAnalysisContainer.appendChild(rightContainer);

            // 计算各行为平均占比
            calculateAverageBehaviors();
        }

        // 计算所有帧中各行为的平均占比
        function calculateAverageBehaviors() {
            // 检查是否有足够的数据
            const videoData = document.processedVideoData;
            if (!videoData || !videoData.processed_result || !Array.isArray(videoData.processed_result)) {
                console.warn('没有可用的视频数据来计算行为平均占比');
                return;
            }

            try {
                // 初始化行为统计和总人数统计
                const behaviors = {
                    '使用手机': 0,
                    '站立': 0,
                    '趴桌': 0,
                    '抬头': 0
                };
                
                let totalPeople = 0;
                let totalTimePoints = 0;
                
                // 如果是新API格式（数组的数组）
                if (Array.isArray(videoData.processed_result[0])) {
                    // 提取各个时间点的数据
                    const timePoints = new Set();
                    videoData.processed_result.forEach(categoryData => {
                        if (Array.isArray(categoryData)) {
                            categoryData.forEach(item => {
                                if (item && item.时间点 !== undefined) {
                                    timePoints.add(item.时间点);
                                }
                            });
                        }
                    });
                    
                    totalTimePoints = timePoints.size;
                    
                    // 提取总人数数据
                    if (videoData.processed_result.length >= 1 && Array.isArray(videoData.processed_result[0])) {
                        videoData.processed_result[0].forEach(item => {
                            if (item && item.总人数 !== undefined) {
                                totalPeople += item.总人数;
                            }
                        });
                    }
                    
                    // 累计各个行为的人数
                    videoData.processed_result.forEach(categoryData => {
                        if (Array.isArray(categoryData)) {
                            categoryData.forEach(item => {
                                if (item) {
                                    if (item.使用手机人数 !== undefined) {
                                        behaviors['使用手机'] += item.使用手机人数;
                                    }
                                    if (item.站立人数 !== undefined) {
                                        behaviors['站立'] += item.站立人数;
                                    }
                                    if (item.趴桌人数 !== undefined) {
                                        behaviors['趴桌'] += item.趴桌人数;
                                    }
                                    if (item.抬头人数 !== undefined) {
                                        behaviors['抬头'] += item.抬头人数;
                                    }
                                }
                            });
                        }
                    });
                }
                
                // 计算平均值
                if (totalTimePoints > 0) {
                    Object.keys(behaviors).forEach(key => {
                        behaviors[key] = behaviors[key] / totalTimePoints;
                    });
                    totalPeople = totalPeople / totalTimePoints;
                }
                
                // 渲染饼图
                renderAverageBehaviorPie(behaviors, totalPeople);
            } catch (error) {
                console.error('计算行为平均占比时出错:', error);
            }
        }

        // 渲染平均行为占比饼图
        function renderAverageBehaviorPie(behaviors, totalPeople) {
            const pieChartDom = document.getElementById('average-behavior-pie-chart');
            if (!pieChartDom || !window.echarts) return;
            
            let myChart = echarts.getInstanceByDom(pieChartDom);
            if (!myChart) {
                myChart = echarts.init(pieChartDom);
            }
            
            // 准备饼图数据
            const pieData = [];
            const colors = {
                '使用手机': '#33FF57',
                '站立': '#3357FF',
                '趴桌': '#9C27B0',
                '抬头': '#FF4081'
            };
            
            // 将行为数据转换为饼图数据格式，基于总人数计算百分比
            Object.entries(behaviors).forEach(([behavior, count]) => {
                if (count > 0) {
                    // 计算占总人数的百分比
                    const percentage = totalPeople > 0 ? (count / totalPeople) * 100 : 0;
                    pieData.push({
                        name: behavior,
                        value: count.toFixed(2),
                        percentage: percentage.toFixed(2),
                        itemStyle: {
                            color: colors[behavior] || '#00f0ff'
                        }
                    });
                }
            });
            
            // 设置饼图选项
            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        return `行为占比 <br/>${params.name}: ${params.value}人 (${params.data.percentage}%)`;
                    },
                    backgroundColor: 'rgba(15, 25, 40, 0.85)',
                    borderColor: 'rgba(0, 240, 255, 0.3)',
                    textStyle: {
                        color: '#e0e0ff'
                    },
                    extraCssText: 'box-shadow: 0 0 10px rgba(0, 240, 255, 0.3);'
                },
                legend: {
                    orient: 'horizontal',
                    bottom: 10,
                    itemWidth: 12,
                    itemHeight: 12,
                    textStyle: {
                        color: '#7adbff',
                        fontSize: 13,
                        fontWeight: '500'
                    },
                    itemGap: 20,
                    data: pieData.map(item => item.name)
                },
                series: [
                    {
                        name: '行为占比',
                        type: 'pie',
                        radius: ['35%', '65%'],
                        center: ['50%', '45%'],
                        avoidLabelOverlap: true,
                        itemStyle: {
                            borderColor: 'rgba(10, 20, 30, 0.2)',
                            borderWidth: 2,
                            shadowBlur: 15,
                            shadowColor: 'rgba(0, 240, 255, 0.3)'
                        },
                        label: {
                            show: true,
                            position: 'outside',
                            formatter: function(params) {
                                return `${params.name}: ${params.data.percentage}%`;
                            },
                            color: '#e0e0ff',
                            fontSize: 13,
                            fontWeight: '500',
                            textShadow: '0 0 3px rgba(0, 0, 0, 0.3)'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: 14,
                                fontWeight: 'bold',
                                color: '#FFFFFF'
                            },
                            itemStyle: {
                                shadowBlur: 25,
                                shadowColor: 'rgba(0, 240, 255, 0.7)',
                                borderWidth: 0
                            }
                        },
                        labelLine: {
                            show: true,
                            length: 15,
                            length2: 10,
                            smooth: true,
                            lineStyle: {
                                color: 'rgba(122, 219, 255, 0.7)',
                                width: 1.5
                            }
                        },
                        data: pieData
                    }
                ],
                animationDuration: 1500,
                animationEasing: 'elasticOut',
                animationDelay: function (idx) {
                    return idx * 100;
                }
            };
            
            myChart.setOption(option);
            
            // 设置响应式调整
            window.addEventListener('resize', () => {
                setTimeout(() => {
                    myChart.resize();
                }, 100);
            });
        }

        // 当页面初始化完成后，创建平均行为饼图
        document.addEventListener('DOMContentLoaded', function() {
            // 页面加载后添加样式
            const style = document.createElement('style');
            style.textContent = `
                .average-behavior-pie-container {
                    padding: 20px;
                    background: rgba(10, 20, 40, 0.8);
                    border-radius: 10px;
                    box-shadow: 0 4px 20px rgba(0, 200, 255, 0.1);
                    max-width: 1200px;
                }
                
                .average-behavior-pie-container h2 {
                    color: #00f0ff;
                    text-align: center;
                    margin-bottom: 10px;
                    font-size: 22px;
                }
                
                .average-behavior-pie-container .chart-tip {
                    text-align: center;
                    color: rgba(0, 240, 255, 0.7);
                    margin-bottom: 20px;
                    font-size: 14px;
                }
                
                #average-behavior-pie-chart {
                    height: 400px;
                    width: 100%;
                }
            `;
            document.head.appendChild(style);
            
            // 监听视频数据加载完成事件
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    if (mutation.type === 'childList' && document.getElementById('video-report-container').children.length > 0) {
                        // 确保视频数据已经加载
                        setTimeout(() => {
                            // 移除可能已存在的底部分析容器
                            const existingContainer = document.getElementById('bottom-analysis-container');
                            if (existingContainer) {
                                existingContainer.remove();
                            }
                            
                            // 创建新的底部分析容器
                            const bottomContainer = document.createElement('div');
                            bottomContainer.id = 'bottom-analysis-container';
                            bottomContainer.className = 'bottom-analysis-container';
                            bottomContainer.style.width = '100%';
                            bottomContainer.style.maxWidth = '100%';
                            bottomContainer.style.marginLeft = 'auto';
                            bottomContainer.style.marginRight = 'auto';
                            bottomContainer.style.padding = '0 5vw';
                            bottomContainer.style.boxSizing = 'border-box';
                            bottomContainer.style.display = 'flex';
                            bottomContainer.style.flexWrap = 'wrap';
                            bottomContainer.style.justifyContent = 'space-between';
                            bottomContainer.style.gap = '6vw';
                            document.body.appendChild(bottomContainer);
                            
                            // 创建柱状图和饼图
                            createAverageBehaviorBarChart();
                            createAverageBehaviorPieChart();
                            
                            // 调整图表宽度，确保充分利用空间
                            setTimeout(() => {
                                const charts = document.querySelectorAll('#average-behavior-bar-chart, #average-behavior-pie-chart');
                                charts.forEach(chart => {
                                    if (chart && window.echarts) {
                                        const chartInstance = echarts.getInstanceByDom(chart);
                                        if (chartInstance) {
                                            chartInstance.resize();
                                        }
                                    }
                                });
                            }, 200);
                            
                            // 为底部容器添加样式
                            const headerStyle = document.createElement('style');
                            headerStyle.textContent = `
                                .bottom-analysis-container {
                                    margin-top: 40px;
                                    width: 100%;
                                    max-width: 100%;
                                    padding: 0 5vw;
                                    box-sizing: border-box;
                                    position: relative;
                                    left: 0;
                                    right: 0;
                                }
                                
                                .analysis-chart-container {
                                    min-width: 45%;
                                }
                            `;
                            document.head.appendChild(headerStyle);
                        }, 1000);
                        observer.disconnect();
                    }
                });
            });
            
            // 开始观察视频报告容器
            const videoReportContainer = document.getElementById('video-report-container');
            if (videoReportContainer) {
                observer.observe(videoReportContainer, { childList: true });
            }
        });

        // 在获取视频数据后存储，以便后续使用
        const originalRenderVideoReport = renderVideoReport;
        renderVideoReport = function(data) {
            // 保存视频数据以供后续使用
            document.processedVideoData = data;
            // 调用原始函数
            originalRenderVideoReport(data);
        };

        // 添加用于显示行为平均人数的柱状图
        function createAverageBehaviorBarChart() {
            // 创建柱状图容器
            const container = document.createElement('div');
            container.className = 'average-behavior-bar-container';
            container.innerHTML = `
                <h2>行为平均人数统计</h2>
                <div class="chart-tip">展示整个视频中各类行为的平均人数</div>
                <div class="bar-chart" id="average-behavior-bar-chart"></div>
            `;
            
            // 检查是否已存在底部分析容器
            let bottomAnalysisContainer = document.getElementById('bottom-analysis-container');
            if (!bottomAnalysisContainer) {
                // 创建底部分析容器
                bottomAnalysisContainer = document.createElement('div');
                bottomAnalysisContainer.id = 'bottom-analysis-container';
                bottomAnalysisContainer.className = 'bottom-analysis-container';
                document.body.appendChild(bottomAnalysisContainer);
            }
            
            // 创建左侧柱状图容器
            const leftContainer = document.createElement('div');
            leftContainer.className = 'analysis-chart-container';
            leftContainer.appendChild(container);
            
            // 将柱状图容器添加到底部分析容器
            bottomAnalysisContainer.appendChild(leftContainer);
            
            // 计算各行为平均人数
            calculateAverageBehaviorCounts();
        }

        // 计算所有帧中各行为的平均人数
        function calculateAverageBehaviorCounts() {
            // 检查是否有足够的数据
            const videoData = document.processedVideoData;
            if (!videoData || !videoData.processed_result || !Array.isArray(videoData.processed_result)) {
                console.warn('没有可用的视频数据来计算行为平均人数');
                return;
            }

            try {
                // 初始化行为统计
                const behaviors = {
                    '使用手机': 0,
                    '站立': 0,
                    '趴桌': 0,
                    '抬头': 0
                };
                
                let totalTimePoints = 0;
                
                // 如果是新API格式（数组的数组）
                if (Array.isArray(videoData.processed_result[0])) {
                    // 提取各个时间点的数据
                    const timePoints = new Set();
                    videoData.processed_result.forEach(categoryData => {
                        if (Array.isArray(categoryData)) {
                            categoryData.forEach(item => {
                                if (item && item.时间点 !== undefined) {
                                    timePoints.add(item.时间点);
                                }
                            });
                        }
                    });
                    
                    totalTimePoints = timePoints.size;
                    
                    // 累计各个行为的人数
                    videoData.processed_result.forEach(categoryData => {
                        if (Array.isArray(categoryData)) {
                            categoryData.forEach(item => {
                                if (item) {
                                    if (item.使用手机人数 !== undefined) {
                                        behaviors['使用手机'] += item.使用手机人数;
                                    }
                                    if (item.站立人数 !== undefined) {
                                        behaviors['站立'] += item.站立人数;
                                    }
                                    if (item.趴桌人数 !== undefined) {
                                        behaviors['趴桌'] += item.趴桌人数;
                                    }
                                    if (item.抬头人数 !== undefined) {
                                        behaviors['抬头'] += item.抬头人数;
                                    }
                                }
                            });
                        }
                    });
                }
                
                // 计算平均值
                if (totalTimePoints > 0) {
                    Object.keys(behaviors).forEach(key => {
                        behaviors[key] = behaviors[key] / totalTimePoints;
                    });
                }
                
                // 渲染柱状图
                renderAverageBehaviorBar(behaviors);
            } catch (error) {
                console.error('计算行为平均人数时出错:', error);
            }
        }

        // 渲染平均行为人数柱状图
        function renderAverageBehaviorBar(behaviors) {
            const barChartDom = document.getElementById('average-behavior-bar-chart');
            if (!barChartDom || !window.echarts) return;
            
            let myChart = echarts.getInstanceByDom(barChartDom);
            if (!myChart) {
                myChart = echarts.init(barChartDom);
            }
            
            // 准备柱状图数据
            const categories = [];
            const values = [];
            const colors = {
                '使用手机': '#33FF57',
                '站立': '#3357FF',
                '趴桌': '#9C27B0',
                '抬头': '#FF4081'
            };
            
            // 将行为数据转换为柱状图数据格式
            Object.entries(behaviors).forEach(([behavior, count]) => {
                if (count > 0) {
                    categories.push(behavior);
                    values.push(parseFloat(count.toFixed(2)));
                }
            });
            
            // 设置柱状图选项
            const option = {
                backgroundColor: 'transparent',
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: '{b}: {c}人',
                    backgroundColor: 'rgba(15, 25, 40, 0.85)',
                    borderColor: 'rgba(0, 240, 255, 0.3)',
                    textStyle: {
                        color: '#e0e0ff'
                    }
                },
                grid: {
                    top: '10%',
                    left: '5%',
                    right: '5%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: categories,
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.4)'
                        }
                    },
                    axisTick: {
                        alignWithLabel: true,
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.4)'
                        }
                    },
                    axisLabel: {
                        color: '#7adbff',
                        fontSize: 13,
                        interval: 0,
                        rotate: 0,
                        fontWeight: '500'
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '平均人数',
                    nameTextStyle: {
                        color: '#7adbff',
                        fontSize: 13,
                        fontWeight: '500'
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.4)'
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(0, 240, 255, 0.15)',
                            type: 'dashed'
                        }
                    },
                    axisLabel: {
                        color: '#7adbff',
                        fontSize: 12
                    }
                },
                series: [{
                    type: 'bar',
                    barWidth: '50%',
                    data: categories.map((category, index) => {
                        return {
                            value: values[index],
                            itemStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    {offset: 0, color: colors[category] || '#00f0ff'},
                                    {offset: 1, color: 'rgba(' + (colors[category] ? hexToRgb(colors[category]) : '0, 240, 255') + ', 0.4)'}
                                ]),
                                borderRadius: [4, 4, 0, 0],
                                shadowColor: 'rgba(0, 240, 255, 0.3)',
                                shadowBlur: 10
                            }
                        };
                    }),
                    label: {
                        show: true,
                        position: 'top',
                        distance: 5,
                        color: '#e0e0ff',
                        fontSize: 13,
                        fontWeight: 'bold',
                        formatter: '{c}'
                    }
                }],
                animationDuration: 1500,
                animationEasing: 'elasticOut'
            };
            
            myChart.setOption(option);
            
            // 设置响应式调整
            window.addEventListener('resize', () => {
                setTimeout(() => {
                    myChart.resize();
                }, 100);
            });
        }

        // 转换十六进制颜色为RGB
        function hexToRgb(hex) {
            // 移除可能的#前缀
            hex = hex.replace('#', '');
            
            // 解析RGB值
            let r = parseInt(hex.substring(0, 2), 16);
            let g = parseInt(hex.substring(2, 4), 16);
            let b = parseInt(hex.substring(4, 6), 16);
            
            return r + ',' + g + ',' + b;
        }

        // 当页面初始化完成后，添加柱状图和饼图的样式
        document.addEventListener('DOMContentLoaded', function() {
            // 页面加载后添加样式
            const style = document.createElement('style');
            style.textContent = `
                .bottom-analysis-container {
                    display: flex;
                    flex-wrap: wrap;
                    justify-content: space-between;
                    margin: 40px 0;
                    max-width: 100%;
                    width: 100%;
                    padding: 0 5vw;
                    gap: 6vw;
                    left: 0;
                    right: 0;
                    position: relative;
                    box-sizing: border-box;
                }
                
                .analysis-chart-container {
                    flex: 1 1 calc(50% - 3vw);
                    min-width: 300px;
                }
                
                .average-behavior-bar-container,
                .average-behavior-pie-container {
                    background: rgba(10, 20, 40, 0.85);
                    border-radius: 12px;
                    box-shadow: 0 0 20px rgba(0, 240, 255, 0.25), inset 0 0 15px rgba(0, 0, 0, 0.2);
                    padding: 25px;
                    height: 100%;
                    border: 1px solid rgba(0, 240, 255, 0.15);
                    backdrop-filter: blur(10px);
                    transition: all 0.4s cubic-bezier(0.19, 1, 0.22, 1);
                    position: relative;
                    overflow: hidden;
                }
                
                .average-behavior-bar-container::before,
                .average-behavior-pie-container::before {
                    content: '';
                    position: absolute;
                    top: -50%;
                    left: -50%;
                    width: 200%;
                    height: 200%;
                    background: linear-gradient(
                        45deg,
                        transparent 0%,
                        rgba(0, 240, 255, 0.05) 50%,
                        transparent 100%
                    );
                    transform: rotate(45deg);
                    animation: glowEffect 6s linear infinite;
                    z-index: -1;
                }
                
                @keyframes glowEffect {
                    0% {
                        transform: rotate(45deg) translateX(-100%);
                    }
                    100% {
                        transform: rotate(45deg) translateX(100%);
                    }
                }
                
                .average-behavior-bar-container:hover,
                .average-behavior-pie-container:hover {
                    box-shadow: 0 0 30px rgba(0, 240, 255, 0.35), inset 0 0 15px rgba(0, 0, 0, 0.2);
                    border: 1px solid rgba(0, 240, 255, 0.3);
                    transform: translateY(-5px);
                }
                
                .average-behavior-bar-container h2,
                .average-behavior-pie-container h2 {
                    color: #00f0ff;
                    text-align: center;
                    margin-bottom: 15px;
                    font-size: 22px;
                    text-shadow: 0 0 15px rgba(0, 240, 255, 0.7);
                    letter-spacing: 1px;
                    position: relative;
                    display: inline-block;
                    width: 100%;
                }
                
                .average-behavior-bar-container h2::after,
                .average-behavior-pie-container h2::after {
                    content: '';
                    position: absolute;
                    width: 60%;
                    height: 2px;
                    bottom: -8px;
                    left: 20%;
                    background: linear-gradient(90deg, 
                        rgba(0, 240, 255, 0) 0%, 
                        rgba(0, 240, 255, 0.7) 50%, 
                        rgba(0, 240, 255, 0) 100%);
                }
                
                .average-behavior-bar-container .chart-tip,
                .average-behavior-pie-container .chart-tip {
                    text-align: center;
                    color: rgba(0, 240, 255, 0.7);
                    margin-bottom: 20px;
                    font-size: 14px;
                    font-weight: 300;
                    letter-spacing: 0.5px;
                }
                
                #average-behavior-bar-chart,
                #average-behavior-pie-chart {
                    height: 380px;
                    width: 100%;
                    margin-top: 10px;
                }
                
                /* 添加响应式布局支持 */
                @media (max-width: 768px) {
                    .bottom-analysis-container {
                        flex-direction: column;
                        padding: 0 5vw;
                    }
                    
                    .analysis-chart-container {
                        flex: 1 1 100%;
                        margin-bottom: 25px;
                    }
                    
                    #average-behavior-bar-chart,
                    #average-behavior-pie-chart {
                        height: 350px;
                    }
                    
                    .average-behavior-bar-container,
                    .average-behavior-pie-container {
                        padding: 20px 15px;
                    }
                    
                    .average-behavior-bar-container h2,
                    .average-behavior-pie-container h2 {
                        font-size: 20px;
                    }
                }
            `;
            document.head.appendChild(style);
            
            // 监听视频数据加载完成事件
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    if (mutation.type === 'childList' && document.getElementById('video-report-container').children.length > 0) {
                        // 确保视频数据已经加载
                        setTimeout(() => {
                            // 移除可能已存在的底部分析容器
                            const existingContainer = document.getElementById('bottom-analysis-container');
                            if (existingContainer) {
                                existingContainer.remove();
                            }
                            
                            // 创建新的底部分析容器
                            const bottomContainer = document.createElement('div');
                            bottomContainer.id = 'bottom-analysis-container';
                            bottomContainer.className = 'bottom-analysis-container';
                            bottomContainer.style.width = '100%';
                            bottomContainer.style.maxWidth = '100%';
                            bottomContainer.style.marginLeft = 'auto';
                            bottomContainer.style.marginRight = 'auto';
                            bottomContainer.style.padding = '0 5vw';
                            bottomContainer.style.boxSizing = 'border-box';
                            bottomContainer.style.display = 'flex';
                            bottomContainer.style.flexWrap = 'wrap';
                            bottomContainer.style.justifyContent = 'space-between';
                            bottomContainer.style.gap = '6vw';
                            document.body.appendChild(bottomContainer);
                            
                            // 创建柱状图和饼图
                            createAverageBehaviorBarChart();
                            createAverageBehaviorPieChart();
                            
                            // 调整图表宽度，确保充分利用空间
                            setTimeout(() => {
                                const charts = document.querySelectorAll('#average-behavior-bar-chart, #average-behavior-pie-chart');
                                charts.forEach(chart => {
                                    if (chart && window.echarts) {
                                        const chartInstance = echarts.getInstanceByDom(chart);
                                        if (chartInstance) {
                                            chartInstance.resize();
                                        }
                                    }
                                });
                            }, 200);
                            
                            // 为底部容器添加样式
                            const headerStyle = document.createElement('style');
                            headerStyle.textContent = `
                                .bottom-analysis-container {
                                    margin-top: 40px;
                                    width: 100vw;
                                    max-width: 100vw;
                                    padding: 0 5vw;
                                    left: 0;
                                    right: 0;
                                    position: relative;
                                    box-sizing: border-box;
                                }
                                
                                #bottom-analysis-container {
                                    width: 100% !important;
                                    max-width: 100% !important;
                                    margin-left: auto !important;
                                    margin-right: auto !important;
                                    position: relative !important;
                                    left: 0 !important;
                                    right: 0 !important;
                                    padding: 0 5vw !important;
                                    box-sizing: border-box !important;
                                }
                            `;
                            document.head.appendChild(headerStyle);
                        }, 1000);
                        observer.disconnect();
                    }
                });
            });
            
            // 开始观察视频报告容器
            const videoReportContainer = document.getElementById('video-report-container');
            if (videoReportContainer) {
                observer.observe(videoReportContainer, { childList: true });
            }
        });

        // 添加高亮当前时间点的函数
        function highlightTimePointInChart(timePoint) {
            if (!trendChartInstance || timePoint === null) return;
            
            // 保存当前时间点用于图表重绘时恢复高亮
            currentTimePoint = timePoint;
            
            // 获取当前图表选项
            const option = trendChartInstance.getOption();
            
            // 查找最接近的时间点索引
            let closestIndex = -1;
            let minDiff = Infinity;
            
            // 获取x轴的原始时间点数据
            const rawTimePoints = option.xAxis[0].data.map(timeStr => {
                // 将时分秒格式转回秒数
                const parts = timeStr.split(':');
                let seconds = 0;
                
                if (parts.length === 2) {
                    // 分:秒 格式
                    seconds = parseInt(parts[0]) * 60 + parseInt(parts[1]);
                } else if (parts.length === 3) {
                    // 时:分:秒 格式
                    seconds = parseInt(parts[0]) * 3600 + parseInt(parts[1]) * 60 + parseInt(parts[2]);
                }
                
                return seconds;
            });
            
            // 找到最接近的时间点
            for (let index = 0; index < rawTimePoints.length; index++) {
                const seconds = rawTimePoints[index];
                const diff = Math.abs(seconds - timePoint);
                
                if (diff < minDiff) {
                    minDiff = diff;
                    closestIndex = index;
                }
            }
            
            if (closestIndex === -1) return;
            
            // 准备高亮点数据
            const highlightData = [];
            
            // 获取图例选择状态
            const legendSelected = option.legend[0].selected;
            
            // 对每个行为系列添加高亮点
            option.series.forEach((series, index) => {
                // 跳过高亮系列本身
                if (series.id === 'highlightSeries') return;
                
                // 检查该系列是否在图例中被选中显示
                if (legendSelected && legendSelected[series.name] === false) {
                    return; // 跳过被隐藏的系列
                }
                
                // 获取该行为在当前时间点的值
                if (series.data && closestIndex < series.data.length) {
                    const value = series.data[closestIndex];
                    
                    // 添加高亮点数据
                    if (value > 0) {
                        highlightData.push({
                            name: series.name,
                            value: [closestIndex, value],
                            itemStyle: {
                                color: series.itemStyle.color,
                                borderColor: '#fff',
                                borderWidth: 2,
                                shadowBlur: 10,
                                shadowColor: '#fff'
                            }
                        });
                    }
                }
            });
            
            // 更新高亮系列数据
            trendChartInstance.setOption({
                series: [{
                    id: 'highlightSeries',
                    data: highlightData
                }]
            });
        }

        // 将秒数转换为时分秒格式的函数
        function secondsToTimeString(seconds) {
            // 计算小时、分钟和秒
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = Math.floor(seconds % 60);
            
            // 根据时长选择显示格式
            if (hours > 0) {
                // 时分秒格式 (hh:mm:ss)
                return `${hours}:${minutes < 10 ? '0' + minutes : minutes}:${secs < 10 ? '0' + secs : secs}`;
            } else {
                // 分秒格式 (mm:ss)
                return `${minutes}:${secs < 10 ? '0' + secs : secs}`;
            }
        }
    </script>
</body>

</html>